file_name
stringlengths
71
779k
comments
stringlengths
20
182k
code_string
stringlengths
20
36.9M
__index_level_0__
int64
0
17.2M
input_ids
sequence
attention_mask
sequence
labels
sequence
./full_match/1/0xDF4c0fcBA2eD81346F06D57bCD80240f77893f5F/sources/contracts/generalIndexModule.sol
* @title IPriceOracle @author Cook Finance Interface for interacting with PriceOracle/
interface IPriceOracle { function getPrice(address _assetOne, address _assetTwo) external view returns (uint256); function masterQuoteAsset() external view returns (address); Copyright 2021 Cook Finance. }
9,637,965
[ 1, 2579, 3057, 23601, 225, 385, 1184, 9458, 1359, 6682, 364, 16592, 310, 598, 20137, 23601, 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, 2971, 3057, 23601, 288, 203, 203, 203, 565, 445, 25930, 12, 2867, 389, 9406, 3335, 16, 1758, 389, 9406, 11710, 13, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 565, 445, 4171, 10257, 6672, 1435, 3903, 1476, 1135, 261, 2867, 1769, 203, 203, 565, 25417, 26599, 21, 385, 1184, 9458, 1359, 18, 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 ]
pragma solidity 0.6.12; import '@pancakeswap/pancake-swap-lib/contracts/math/SafeMath.sol'; import '@pancakeswap/pancake-swap-lib/contracts/token/BEP20/IBEP20.sol'; import '@pancakeswap/pancake-swap-lib/contracts/token/BEP20/SafeBEP20.sol'; import '@pancakeswap/pancake-swap-lib/contracts/access/Ownable.sol'; import "./MySecure.sol"; import "./SyrupBar.sol"; // import "@nomiclabs/buidler/console.sol"; interface IMigratorChef { // Perform LP token migration from legacy SilverlineSwap to CakeSwap. // Take the current LP token address and return the new LP token address. // Migrator should have full access to the caller's LP token. // Return the new LP token address. // // XXX Migrator must have allowance access to SilverlineSwap LP tokens. // CakeSwap must mint EXACTLY the same amount of CakeSwap LP tokens or // else something bad will happen. Traditional SilverlineSwap does not // do that so be careful! function migrate(IBEP20 token) external returns (IBEP20); } // MasterChef is the master of Silver. He can make Silver and he is a fair guy. // // Note that it's ownable and the owner wields tremendous power. The ownership // will be transferred to a governance smart contract once SILVER is sufficiently // distributed and the community can show to govern itself. // // Have fun reading it. Hopefully it's bug-free. God bless. contract MasterChef is Ownable { using SafeMath for uint256; using SafeBEP20 for IBEP20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of SILVERs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accCakePerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accCakePerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IBEP20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. SILVERs to distribute per block. uint256 lastRewardBlock; // Last block number that SILVERs distribution occurs. uint256 accCakePerShare; // Accumulated SILVERs per share, times 1e12. See below. } // The SILVER TOKEN! MySecure public cake; // The SYRUP TOKEN! SyrupBar public syrup; // Dev address. address public devaddr; // SILVER tokens created per block. uint256 public cakePerBlock; // Bonus muliplier for early cake makers. uint256 public BONUS_MULTIPLIER = 1; // The migrator contract. It has a lot of power. Can only be set through governance (owner). IMigratorChef public migrator; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping (uint256 => mapping (address => UserInfo)) public userInfo; // Total allocation points. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when SILVER mining starts. uint256 public startBlock; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); constructor( MySecure _cake, SyrupBar _syrup, address _devaddr, uint256 _cakePerBlock, uint256 _startBlock ) public { cake = _cake; syrup = _syrup; devaddr = _devaddr; cakePerBlock = _cakePerBlock; startBlock = _startBlock; // staking pool poolInfo.push(PoolInfo({ lpToken: _cake, allocPoint: 1000, lastRewardBlock: startBlock, accCakePerShare: 0 })); totalAllocPoint = 1000; } function updateMultiplier(uint256 multiplierNumber) public onlyOwner { BONUS_MULTIPLIER = multiplierNumber; } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add(uint256 _allocPoint, IBEP20 _lpToken, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accCakePerShare: 0 })); updateStakingPool(); } // Update the given pool's SILVER allocation point. Can only be called by the owner. function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 prevAllocPoint = poolInfo[_pid].allocPoint; poolInfo[_pid].allocPoint = _allocPoint; if (prevAllocPoint != _allocPoint) { totalAllocPoint = totalAllocPoint.sub(prevAllocPoint).add(_allocPoint); updateStakingPool(); } } function updateStakingPool() internal { uint256 length = poolInfo.length; uint256 points = 0; for (uint256 pid = 1; pid < length; ++pid) { points = points.add(poolInfo[pid].allocPoint); } if (points != 0) { points = points.div(3); totalAllocPoint = totalAllocPoint.sub(poolInfo[0].allocPoint).add(points); poolInfo[0].allocPoint = points; } } // Set the migrator contract. Can only be called by the owner. function setMigrator(IMigratorChef _migrator) public onlyOwner { migrator = _migrator; } // Migrate lp token to another lp contract. Can be called by anyone. We trust that migrator contract is good. function migrate(uint256 _pid) public { require(address(migrator) != address(0), "migrate: no migrator"); PoolInfo storage pool = poolInfo[_pid]; IBEP20 lpToken = pool.lpToken; uint256 bal = lpToken.balanceOf(address(this)); lpToken.safeApprove(address(migrator), bal); IBEP20 newLpToken = migrator.migrate(lpToken); require(bal == newLpToken.balanceOf(address(this)), "migrate: bad"); pool.lpToken = newLpToken; } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { return _to.sub(_from).mul(BONUS_MULTIPLIER); } // View function to see pending SILVERs on frontend. function pendingCake(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accCakePerShare = pool.accCakePerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 cakeReward = multiplier.mul(cakePerBlock).mul(pool.allocPoint).div(totalAllocPoint); accCakePerShare = accCakePerShare.add(cakeReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accCakePerShare).div(1e12).sub(user.rewardDebt); } // Update reward variables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 cakeReward = multiplier.mul(cakePerBlock).mul(pool.allocPoint).div(totalAllocPoint); cake.mint(devaddr, cakeReward.div(10)); cake.mint(address(syrup), cakeReward); pool.accCakePerShare = pool.accCakePerShare.add(cakeReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; } // Deposit LP tokens to MasterChef for SILVER allocation. function deposit(uint256 _pid, uint256 _amount) public { require (_pid != 0, 'deposit SILVER by staking'); PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accCakePerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeCakeTransfer(msg.sender, pending); } } if (_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); } user.rewardDebt = user.amount.mul(pool.accCakePerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Withdraw LP tokens from MasterChef. function withdraw(uint256 _pid, uint256 _amount) public { require (_pid != 0, 'withdraw SILVER by unstaking'); PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accCakePerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeCakeTransfer(msg.sender, pending); } if(_amount > 0) { user.amount = user.amount.sub(_amount); pool.lpToken.safeTransfer(address(msg.sender), _amount); } user.rewardDebt = user.amount.mul(pool.accCakePerShare).div(1e12); emit Withdraw(msg.sender, _pid, _amount); } // Stake SILVER tokens to MasterChef function enterStaking(uint256 _amount) public { PoolInfo storage pool = poolInfo[0]; UserInfo storage user = userInfo[0][msg.sender]; updatePool(0); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accCakePerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeCakeTransfer(msg.sender, pending); } } if(_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); } user.rewardDebt = user.amount.mul(pool.accCakePerShare).div(1e12); syrup.mint(msg.sender, _amount); emit Deposit(msg.sender, 0, _amount); } // Withdraw SILVER tokens from STAKING. function leaveStaking(uint256 _amount) public { PoolInfo storage pool = poolInfo[0]; UserInfo storage user = userInfo[0][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(0); uint256 pending = user.amount.mul(pool.accCakePerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeCakeTransfer(msg.sender, pending); } if(_amount > 0) { user.amount = user.amount.sub(_amount); pool.lpToken.safeTransfer(address(msg.sender), _amount); } user.rewardDebt = user.amount.mul(pool.accCakePerShare).div(1e12); syrup.burn(msg.sender, _amount); emit Withdraw(msg.sender, 0, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; pool.lpToken.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; } // Safe cake transfer function, just in case if rounding error causes pool to not have enough SILVERs. function safeCakeTransfer(address _to, uint256 _amount) internal { syrup.safeCakeTransfer(_to, _amount); } // Update dev address by the previous dev. function dev(address _devaddr) public { require(msg.sender == devaddr, "dev: wut?"); devaddr = _devaddr; } } // SPDX-License-Identifier: MIT pragma solidity >=0.4.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, 'SafeMath: addition overflow'); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, 'SafeMath: subtraction overflow'); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, 'SafeMath: multiplication overflow'); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, 'SafeMath: division by zero'); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, 'SafeMath: modulo by zero'); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } function min(uint256 x, uint256 y) internal pure returns (uint256 z) { z = x < y ? x : y; } // babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method) function sqrt(uint256 y) internal pure returns (uint256 z) { if (y > 3) { z = y; uint256 x = y / 2 + 1; while (x < z) { z = x; x = (y / x + x) / 2; } } else if (y != 0) { z = 1; } } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity >=0.4.0; interface IBEP20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the token decimals. */ function decimals() external view returns (uint8); /** * @dev Returns the token symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the token name. */ function name() external view returns (string memory); /** * @dev Returns the bep token owner. */ function getOwner() external view returns (address); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address _owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import './IBEP20.sol'; import '../../math/SafeMath.sol'; import '../../utils/Address.sol'; /** * @title SafeBEP20 * @dev Wrappers around BEP20 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 SafeBEP20 for IBEP20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeBEP20 { using SafeMath for uint256; using Address for address; function safeTransfer( IBEP20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IBEP20 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 * {IBEP20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IBEP20 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), 'SafeBEP20: approve from non-zero to non-zero allowance' ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IBEP20 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( IBEP20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender).sub( value, 'SafeBEP20: 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(IBEP20 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, 'SafeBEP20: low-level call failed'); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), 'SafeBEP20: BEP20 operation did not succeed'); } } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity >=0.4.0; import '../GSN/Context.sol'; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), 'Ownable: caller is not the owner'); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), 'Ownable: new owner is the zero address'); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } pragma solidity 0.6.12; import "@pancakeswap/pancake-swap-lib/contracts/token/BEP20/BEP20.sol"; // MySecure with Governance. contract MySecure is BEP20('MySecure', 'MYSEC') { /// @notice Creates `_amount` token to `_to`. Must only be called by the owner (MasterChef). function mint(address _to, uint256 _amount) public onlyOwner { _mint(_to, _amount); _moveDelegates(address(0), _delegates[_to], _amount); } // Copied and modified from YAM code: // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol // Which is copied and modified from COMPOUND: // https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol /// @notice A record of each accounts delegate mapping (address => address) internal _delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint256 votes; } /// @notice A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /// @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegator The address to get delegatee for */ function delegates(address delegator) external view returns (address) { return _delegates[delegator]; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) external { return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig( address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s ) external { bytes32 domainSeparator = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this) ) ); bytes32 structHash = keccak256( abi.encode( DELEGATION_TYPEHASH, delegatee, nonce, expiry ) ); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", domainSeparator, structHash ) ); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "MYSEC::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "MYSEC::delegateBySig: invalid nonce"); require(now <= expiry, "MYSEC::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint256) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, "MYSEC::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = _delegates[delegator]; uint256 delegatorBalance = balanceOf(delegator); // balance of underlying SILVERs (not scaled); _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { // decrease old representative uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { // increase new representative uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes ) internal { uint32 blockNumber = safe32(block.number, "MYSEC::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function getChainId() internal pure returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } } pragma solidity 0.6.12; import "@pancakeswap/pancake-swap-lib/contracts/token/BEP20/BEP20.sol"; import "./MySecure.sol"; // SyrupBar with Governance. contract SyrupBar is BEP20('SyrupBar Token', 'SYRUP') { /// @notice Creates `_amount` token to `_to`. Must only be called by the owner (MasterChef). function mint(address _to, uint256 _amount) public onlyOwner { _mint(_to, _amount); _moveDelegates(address(0), _delegates[_to], _amount); } function burn(address _from ,uint256 _amount) public onlyOwner { _burn(_from, _amount); _moveDelegates(_delegates[_from], address(0), _amount); } // The SILVER TOKEN! MySecure public cake; constructor( MySecure _cake ) public { cake = _cake; } // Safe cake transfer function, just in case if rounding error causes pool to not have enough SILVERs. function safeCakeTransfer(address _to, uint256 _amount) public onlyOwner { uint256 cakeBal = cake.balanceOf(address(this)); if (_amount > cakeBal) { cake.transfer(_to, cakeBal); } else { cake.transfer(_to, _amount); } } // Copied and modified from YAM code: // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol // Which is copied and modified from COMPOUND: // https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol /// @notice A record of each accounts delegate mapping (address => address) internal _delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint256 votes; } /// @notice A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegator The address to get delegatee for */ function delegates(address delegator) external view returns (address) { return _delegates[delegator]; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) external { return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig( address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s ) external { bytes32 domainSeparator = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this) ) ); bytes32 structHash = keccak256( abi.encode( DELEGATION_TYPEHASH, delegatee, nonce, expiry ) ); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", domainSeparator, structHash ) ); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "MYSEC::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "MYSEC::delegateBySig: invalid nonce"); require(now <= expiry, "MYSEC::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint256) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, "MYSEC::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = _delegates[delegator]; uint256 delegatorBalance = balanceOf(delegator); // balance of underlying SILVERs (not scaled); _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { // decrease old representative uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { // increase new representative uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes ) internal { uint32 blockNumber = safe32(block.number, "MYSEC::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function getChainId() internal pure returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // 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); } } } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity >=0.4.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor() internal {} function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity >=0.4.0; import '../../access/Ownable.sol'; import '../../GSN/Context.sol'; import './IBEP20.sol'; import '../../math/SafeMath.sol'; import '../../utils/Address.sol'; /** * @dev Implementation of the {IBEP20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {BEP20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-BEP20-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 BEP20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IBEP20-approve}. */ contract BEP20 is Context, IBEP20, Ownable { 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 bep token owner. */ function getOwner() external override view returns (address) { return owner(); } /** * @dev Returns the token name. */ function name() public override view returns (string memory) { return _name; } /** * @dev Returns the token decimals. */ function decimals() public override view returns (uint8) { return _decimals; } /** * @dev Returns the token symbol. */ function symbol() public override view returns (string memory) { return _symbol; } /** * @dev See {BEP20-totalSupply}. */ function totalSupply() public override view returns (uint256) { return _totalSupply; } /** * @dev See {BEP20-balanceOf}. */ function balanceOf(address account) public override view returns (uint256) { return _balances[account]; } /** * @dev See {BEP20-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 override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {BEP20-allowance}. */ function allowance(address owner, address spender) public override view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {BEP20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {BEP20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {BEP20}; * * 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 override returns (bool) { _transfer(sender, recipient, amount); _approve( sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, 'BEP20: 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 {BEP20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(_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 {BEP20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, 'BEP20: decreased allowance below zero') ); return true; } /** * @dev Creates `amount` tokens and assigns them to `msg.sender`, increasing * the total supply. * * Requirements * * - `msg.sender` must be the token owner */ function mint(uint256 amount) public onlyOwner returns (bool) { _mint(_msgSender(), amount); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal { require(sender != address(0), 'BEP20: transfer from the zero address'); require(recipient != address(0), 'BEP20: transfer to the zero address'); _balances[sender] = _balances[sender].sub(amount, 'BEP20: 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 { require(account != address(0), 'BEP20: mint to the zero address'); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal { require(account != address(0), 'BEP20: burn from the zero address'); _balances[account] = _balances[account].sub(amount, 'BEP20: 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 { require(owner != address(0), 'BEP20: approve from the zero address'); require(spender != address(0), 'BEP20: approve to the zero address'); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @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 { _burn(account, amount); _approve( account, _msgSender(), _allowances[account][_msgSender()].sub(amount, 'BEP20: burn amount exceeds allowance') ); } }
* @dev Returns the bep token owner./
function getOwner() external override view returns (address) { return owner(); }
250,528
[ 1, 1356, 326, 506, 84, 1147, 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, 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, 13782, 1435, 3903, 3849, 1476, 1135, 261, 2867, 13, 288, 203, 3639, 327, 3410, 5621, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.4; contract Token { /// @return total amount of tokens function totalSupply() constant returns (uint256 supply) {} /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) constant returns (uint256 balance) {} /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _value) returns (bool success) {} /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {} /// @notice `msg.sender` approves `_addr` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of wei to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint256 _value) returns (bool success) {} /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) constant returns (uint256 remaining) {} event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } contract StandardToken is Token { function transfer(address _to, uint256 _value) returns (bool success) { //Default assumes totalSupply can't be over max (2^256 - 1). //If your token leaves out totalSupply and can issue more tokens as time goes on, you need to check if it doesn't wrap. //Replace the if with this one instead. //if (balances[msg.sender] >= _value && balances[_to] + _value > balances[_to]) { if (balances[msg.sender] >= _value && _value > 0) { balances[msg.sender] -= _value; balances[_to] += _value; Transfer(msg.sender, _to, _value); return true; } else { return false; } } function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { //same as above. Replace this line with the following if you want to protect against wrapping uints. //if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && balances[_to] + _value > balances[_to]) { if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) { balances[_to] += _value; balances[_from] -= _value; allowed[_from][msg.sender] -= _value; Transfer(_from, _to, _value); return true; } else { return false; } } function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } function approve(address _spender, uint256 _value) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; uint256 public totalSupply; } contract InfinitiEstate is StandardToken { // CHANGE THIS. Update the contract name. /* Public variables of the token */ /* NOTE:*************************I N F I N I T I E S T A T E ***************************** ********I N F I N I T I E S T A T E *************I N F I N I T I E S T A T E **** ********I N F I N I T I E S T A T E **************I N F I N I T I E S T A T E ************I N F I N I T I E S T A T E ************I N F I N I T I E S T A T E **** ********I N F I N I T I E S T A T E **************I N F I N I T I E S T A T E ***********I N F I N I T I E S T A T E *************I N F I N I T I E S T A T E ** *************I N F I N I T I E S T A T E **************I N F I N I T I E S T A T E */ string public name; // Token uint8 public decimals; // How many decimals to show. To be standard complicant keep it 18 string public symbol; // An identifier: .. string public version = 'H1.0'; uint256 public InfinitiEstate ; // How many units of your coin can be bought by 1 ETH? uint256 public totalEthInWei; // WEI is the smallest unit of ETH (the equivalent of cent in USD or satoshi in BTC). We'll store the total ETH raised via our ICO here. address fundsWallet; // Where should the raised ETH go? // This is a constructor function // which means the following function name has to match the contract name declared above function InfinitiEstate() { balances[msg.sender] = 220000000000000000000000000; // Give the creator all initial tokens. This is set to 1000 for example. If you want your initial tokens to be X and your decimal is 5, set this value to X * 100000. (CHANGE THIS) totalSupply = 220000000000000000000000000; // Update total supply (1000 for example) (InfinitiEstate) name = "InfinitiEstate"; // Set the name for display purposes (InfinitiEstate) decimals = 18; // Amount of decimals for display purposes (InfinitiEstate) symbol = "INF"; // Set the symbol for display purposes (InfinitiEstate) // Set the price of your token for the ICO (InfinitiEstate) fundsWallet = msg.sender; // The owner of the contract gets ETH } /* Approves and then calls the receiving contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); //call the receiveApproval function on the contract you want to be notified. This crafts the function signature manually so one doesn't have to include a contract in here just for this. //receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData) //it is assumed that when does this that the call *should* succeed, otherwise one would use vanilla approve instead. if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; } return true; } }
Set the symbol for display purposes (InfinitiEstate)
symbol = "INF";
173,711
[ 1, 694, 326, 3273, 364, 2562, 13694, 261, 382, 926, 305, 77, 41, 2019, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 3273, 273, 315, 19212, 14432, 4766, 2868, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.4.24; /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { /** * @dev Subtracts uint16 two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub16(uint16 _a, uint16 _b) internal pure returns (uint16) { require(_b <= _a, 'Sub operation underflowed!'); uint16 c = _a - _b; return c; } /** * @dev Adds two uint16 numbers, reverts on overflow. */ function add16(uint16 _a, uint16 _b) internal pure returns (uint16) { uint16 c = _a + _b; require(c >= _a, 'Add operation overflowed!'); return c; } /** * @dev Multiplies two uint256 numbers, reverts on overflow. */ function mul(uint256 _a, uint256 _b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (_a == 0) { return 0; } uint256 c = _a * _b; require(c / _a == _b, 'Mul operation overflowed!'); return c; } /** * @dev Subtracts two uint256 numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { require(_b <= _a, 'Sub operation underflowed!'); uint256 c = _a - _b; return c; } /** * @dev Adds two uint256 numbers, reverts on overflow. */ function add(uint256 _a, uint256 _b) internal pure returns (uint256) { uint256 c = _a + _b; require(c >= _a, 'Add operation overflowed!'); return c; } }
* @title SafeMath @dev Math operations with safety checks that revert on error/
library SafeMath { function sub16(uint16 _a, uint16 _b) internal pure returns (uint16) { require(_b <= _a, 'Sub operation underflowed!'); uint16 c = _a - _b; return c; } function add16(uint16 _a, uint16 _b) internal pure returns (uint16) { uint16 c = _a + _b; require(c >= _a, 'Add operation overflowed!'); 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, 'Mul operation overflowed!'); 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, 'Mul operation overflowed!'); return c; } function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { require(_b <= _a, 'Sub operation underflowed!'); uint256 c = _a - _b; return c; } function add(uint256 _a, uint256 _b) internal pure returns (uint256) { uint256 c = _a + _b; require(c >= _a, 'Add operation overflowed!'); return c; } }
14,016,385
[ 1, 9890, 10477, 225, 2361, 5295, 598, 24179, 4271, 716, 15226, 603, 555, 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, 12083, 14060, 10477, 288, 203, 202, 915, 720, 2313, 12, 11890, 2313, 389, 69, 16, 2254, 2313, 389, 70, 13, 2713, 16618, 1135, 261, 11890, 2313, 13, 288, 203, 202, 202, 6528, 24899, 70, 1648, 389, 69, 16, 296, 1676, 1674, 3613, 2426, 329, 5124, 1769, 203, 202, 202, 11890, 2313, 276, 273, 389, 69, 300, 389, 70, 31, 203, 203, 202, 202, 2463, 276, 31, 203, 202, 97, 203, 203, 202, 915, 527, 2313, 12, 11890, 2313, 389, 69, 16, 2254, 2313, 389, 70, 13, 2713, 16618, 1135, 261, 11890, 2313, 13, 288, 203, 202, 202, 11890, 2313, 276, 273, 389, 69, 397, 389, 70, 31, 203, 202, 202, 6528, 12, 71, 1545, 389, 69, 16, 296, 986, 1674, 9391, 329, 5124, 1769, 203, 203, 202, 202, 2463, 276, 31, 203, 202, 97, 203, 203, 202, 915, 14064, 12, 11890, 5034, 389, 69, 16, 2254, 5034, 389, 70, 13, 2713, 16618, 1135, 261, 11890, 5034, 13, 288, 203, 202, 202, 430, 261, 67, 69, 422, 374, 13, 288, 203, 1082, 202, 2463, 374, 31, 203, 202, 202, 97, 203, 203, 202, 202, 11890, 5034, 276, 273, 389, 69, 380, 389, 70, 31, 203, 202, 202, 6528, 12, 71, 342, 389, 69, 422, 389, 70, 16, 296, 27860, 1674, 9391, 329, 5124, 1769, 203, 203, 202, 202, 2463, 276, 31, 203, 202, 97, 203, 203, 202, 915, 14064, 12, 11890, 5034, 389, 69, 16, 2254, 5034, 389, 70, 13, 2713, 16618, 1135, 261, 11890, 5034, 13, 288, 203, 202, 202, 430, 261, 67, 69, 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,486,073
[ 1, 145, 253, 145, 127, 146, 235, 145, 123, 145, 113, 225, 145, 115, 145, 120, 145, 116, 145, 124, 146, 242, 145, 126, 146, 230, 145, 124, 145, 113, 225, 145, 126, 145, 113, 225, 145, 125, 146, 238, 146, 235, 145, 123, 146, 230, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 8010, 67, 502, 2038, 30, 145, 115, 145, 120, 145, 116, 145, 124, 146, 242, 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, -100, -100, -100, -100, -100 ]
pragma solidity 0.5.9; import "../contracts_common/Libraries/SafeMathWithRequire.sol"; import "../contracts_common/Interfaces/ERC20.sol"; import "../contracts_common/Interfaces/Medianizer.sol"; import "../contracts_common/BaseWithStorage/Admin.sol"; import "../Asset/ERC1155ERC721.sol"; contract BundleSandSale is Admin { bytes4 private constant ERC1155_RECEIVED = 0xf23a6e61; bytes4 private constant ERC1155_BATCH_RECEIVED = 0xbc197c81; event BundleSale( uint256 indexed saleId, uint256[] ids, uint256[] amounts, uint256 sandAmount, uint256 priceUSD, uint256 numPacks ); event BundleSold( uint256 indexed saleId, address indexed buyer, uint256 numPacks, address token, uint256 tokenAmount ); using SafeMathWithRequire for uint256; Medianizer private _medianizer; ERC20 private _dai; ERC20 private _sand; ERC1155ERC721 private _asset; address payable private _receivingWallet; struct Sale { uint256[] ids; uint256[] amounts; uint256 sandAmount; uint256 priceUSD; uint256 numPacksLeft; } Sale[] private sales; constructor( address sandTokenContractAddress, address assetTokenContractAddress, address medianizerContractAddress, address daiTokenContractAddress, address admin, address payable receivingWallet ) public { require(receivingWallet != address(0), "need a wallet to receive funds"); _medianizer = Medianizer(medianizerContractAddress); _sand = ERC20(sandTokenContractAddress); _asset = ERC1155ERC721(assetTokenContractAddress); _dai = ERC20(daiTokenContractAddress); _admin = admin; _receivingWallet = receivingWallet; } /// @notice set the wallet receiving the proceeds /// @param newWallet address of the new receiving wallet function setReceivingWallet(address payable newWallet) external { require(newWallet != address(0), "receiving wallet cannot be zero address"); require(msg.sender == _admin, "only admin can change the receiving wallet"); _receivingWallet = newWallet; } function _transferPack(uint256 saleIndex, uint256 numPacks, address to) internal { uint256 sandAmountPerPack = sales[saleIndex].sandAmount; require( _sand.transferFrom(address(this), to, sandAmountPerPack.mul(numPacks)), "Sand Transfer failed" ); uint256[] memory ids = sales[saleIndex].ids; uint256[] memory amounts = sales[saleIndex].amounts; uint256 numIds = ids.length; for (uint256 i = 0; i < numIds; i++) { amounts[i] = amounts[i].mul(numPacks); } _asset.safeBatchTransferFrom(address(this), to, ids, amounts, ""); } /** * @notice Buys Sand Bundle with Ether * @param saleId id of the bundle * @param numPacks the amount of packs to buy * @param to The address that will receive the SAND */ function buyBundleWithEther(uint256 saleId, uint256 numPacks, address to) external payable { require(saleId > 0, "invalid saleId"); uint256 saleIndex = saleId - 1; uint256 numPacksLeft = sales[saleIndex].numPacksLeft; require(numPacksLeft >= numPacks, "not enough packs on sale"); sales[saleIndex].numPacksLeft = numPacksLeft - numPacks; uint256 USDRequired = numPacks.mul(sales[saleIndex].priceUSD); uint256 ETHRequired = getEtherAmountWithUSD(USDRequired); require(msg.value >= ETHRequired, "not enough ether sent"); uint256 leftOver = msg.value - ETHRequired; if(leftOver > 0) { msg.sender.transfer(leftOver); // refund extra } address(_receivingWallet).transfer(ETHRequired); _transferPack(saleIndex, numPacks, to); emit BundleSold(saleId, msg.sender, numPacks, address(0), ETHRequired); } /** * @notice Buys Sand Bundle with DAI * @param saleId id of the bundle * @param numPacks the amount of packs to buy * @param to The address that will receive the SAND */ function buyBundleWithDai(uint256 saleId, uint256 numPacks, address to) external { require(saleId > 0, "invalid saleId"); uint256 saleIndex = saleId - 1; uint256 numPacksLeft = sales[saleIndex].numPacksLeft; require(numPacksLeft >= numPacks, "not enough packs on sale"); sales[saleIndex].numPacksLeft = numPacksLeft - numPacks; uint256 USDRequired = numPacks.mul(sales[saleIndex].priceUSD); require(_dai.transferFrom(msg.sender, _receivingWallet, USDRequired), "failed to transfer dai"); _transferPack(saleIndex, numPacks, to); emit BundleSold(saleId, msg.sender, numPacks, address(_dai), USDRequired); } function getSaleInfo(uint256 saleId) external view returns(uint256 priceUSD, uint256 numPacksLeft) { require(saleId > 0, "invalid saleId"); uint256 saleIndex = saleId - 1; priceUSD = sales[saleIndex].priceUSD; numPacksLeft = sales[saleIndex].numPacksLeft; } function withdrawSale(uint256 saleId, address to) external onlyAdmin() { require(saleId > 0, "invalid saleId"); uint256 saleIndex = saleId - 1; uint256 numPacksLeft = sales[saleIndex].numPacksLeft; sales[saleIndex].numPacksLeft = 0; uint256[] memory ids = sales[saleIndex].ids; uint256[] memory amounts = sales[saleIndex].amounts; uint256 numIds = ids.length; for (uint256 i = 0; i < numIds; i++) { amounts[i] = amounts[i].mul(numPacksLeft); } require(_sand.transferFrom(address(this), to, numPacksLeft.mul(sales[saleIndex].sandAmount)), "transfer fo Sand failed"); _asset.safeBatchTransferFrom(address(this), to, ids, amounts, ""); } /** * @notice Returns the amount of ETH for a specific amount of USD * @param usdAmount An amount of USD * @return The amount of ETH */ function getEtherAmountWithUSD(uint256 usdAmount) public view returns (uint256) { uint256 ethUsdPair = getEthUsdPair(); return usdAmount.mul(1000000000000000000).div(ethUsdPair); } /** * @notice Gets the ETHUSD pair from the Medianizer contract * @return The pair as an uint256 */ function getEthUsdPair() internal view returns (uint256) { bytes32 pair = _medianizer.read(); return uint256(pair); } function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external returns (bytes4) { require( address(_asset) == msg.sender, "only accept asset as sender" ); require(from == operator, "only self executed transfer allowed"); require(value > 0, "no Asset transfered"); require(data.length > 0, "data need to contains the sale data"); ( uint256 numPacks, uint256 sandAmountPerPack, uint256 priceUSDPerPack ) = abi.decode(data, (uint256, uint256, uint256)); uint256 amount = value.div(numPacks); require(amount.mul(numPacks) == value, "invalid amounts, not divisible by numPacks"); uint256[] memory amounts = new uint256[](1); amounts[0] = amount; uint256[] memory ids = new uint256[](1); ids[0] = id; _setupBundle(from, sandAmountPerPack, numPacks, ids, amounts, priceUSDPerPack); return ERC1155_RECEIVED; } function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external returns (bytes4) { require( address(_asset) == msg.sender, "only accept asset as sender" ); require(from == operator, "only self executed transfer allowed"); require(ids.length > 0, "need to contains Asset"); require(data.length > 0, "data need to contains the sale data"); ( uint256 numPacks, uint256 sandAmountPerPack, uint256 priceUSDPerPack ) = abi.decode(data, (uint256, uint256, uint256)); uint256[] memory amounts = new uint256[](ids.length); // TODO for(uint256 i = 0; i < amounts.length; i ++) { require(values[i] > 0, "asset transfer with zero values"); uint256 amount = values[i].div(numPacks); require(amount.mul(numPacks) == values[i], "invalid amounts, not divisible by numPacks"); amounts[i] = amount; } _setupBundle(from, sandAmountPerPack, numPacks, ids, amounts, priceUSDPerPack); return ERC1155_BATCH_RECEIVED; } function _setupBundle( address from, uint256 sandAmountPerPack, uint256 numPacks, uint256[] memory ids, uint256[] memory amounts, uint256 priceUSDPerPack ) internal { require(_sand.transferFrom(from, address(this), sandAmountPerPack.mul(numPacks)), "failed to transfer Sand"); uint256 saleId = sales.push(Sale({ ids: ids, amounts : amounts, sandAmount: sandAmountPerPack, priceUSD: priceUSDPerPack, numPacksLeft: numPacks })); emit BundleSale(saleId, ids, amounts, sandAmountPerPack, priceUSDPerPack, numPacks); } }
* @notice Buys Sand Bundle with Ether @param saleId id of the bundle @param numPacks the amount of packs to buy @param to The address that will receive the SAND/
function buyBundleWithEther(uint256 saleId, uint256 numPacks, address to) external payable { require(saleId > 0, "invalid saleId"); uint256 saleIndex = saleId - 1; uint256 numPacksLeft = sales[saleIndex].numPacksLeft; require(numPacksLeft >= numPacks, "not enough packs on sale"); sales[saleIndex].numPacksLeft = numPacksLeft - numPacks; uint256 USDRequired = numPacks.mul(sales[saleIndex].priceUSD); uint256 ETHRequired = getEtherAmountWithUSD(USDRequired); require(msg.value >= ETHRequired, "not enough ether sent"); uint256 leftOver = msg.value - ETHRequired; if(leftOver > 0) { } address(_receivingWallet).transfer(ETHRequired); _transferPack(saleIndex, numPacks, to); emit BundleSold(saleId, msg.sender, numPacks, address(0), ETHRequired); }
2,516,282
[ 1, 38, 89, 1900, 348, 464, 8539, 598, 512, 1136, 225, 272, 5349, 548, 612, 434, 326, 3440, 225, 818, 4420, 87, 326, 3844, 434, 2298, 87, 358, 30143, 225, 358, 1021, 1758, 716, 903, 6798, 326, 348, 4307, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 30143, 3405, 1190, 41, 1136, 12, 11890, 5034, 272, 5349, 548, 16, 2254, 5034, 818, 4420, 87, 16, 1758, 358, 13, 3903, 8843, 429, 288, 203, 3639, 2583, 12, 87, 5349, 548, 405, 374, 16, 315, 5387, 272, 5349, 548, 8863, 203, 3639, 2254, 5034, 272, 5349, 1016, 273, 272, 5349, 548, 300, 404, 31, 203, 3639, 2254, 5034, 818, 4420, 87, 3910, 273, 272, 5408, 63, 87, 5349, 1016, 8009, 2107, 4420, 87, 3910, 31, 203, 3639, 2583, 12, 2107, 4420, 87, 3910, 1545, 818, 4420, 87, 16, 315, 902, 7304, 2298, 87, 603, 272, 5349, 8863, 203, 3639, 272, 5408, 63, 87, 5349, 1016, 8009, 2107, 4420, 87, 3910, 273, 818, 4420, 87, 3910, 300, 818, 4420, 87, 31, 203, 203, 3639, 2254, 5034, 587, 9903, 3705, 273, 818, 4420, 87, 18, 16411, 12, 87, 5408, 63, 87, 5349, 1016, 8009, 8694, 3378, 40, 1769, 203, 3639, 2254, 5034, 512, 2455, 3705, 273, 4774, 1136, 6275, 1190, 3378, 40, 12, 3378, 40, 3705, 1769, 203, 3639, 2583, 12, 3576, 18, 1132, 1545, 512, 2455, 3705, 16, 315, 902, 7304, 225, 2437, 3271, 8863, 203, 3639, 2254, 5034, 2002, 4851, 273, 1234, 18, 1132, 300, 512, 2455, 3705, 31, 203, 3639, 309, 12, 4482, 4851, 405, 374, 13, 288, 203, 3639, 289, 203, 3639, 1758, 24899, 8606, 9288, 16936, 2934, 13866, 12, 1584, 44, 3705, 1769, 203, 3639, 389, 13866, 4420, 12, 87, 5349, 1016, 16, 818, 4420, 87, 16, 358, 1769, 203, 203, 3639, 3626, 8539, 55, 1673, 12, 87, 2 ]
pragma solidity ^0.4.24; import "@aragon/os/contracts/apps/AragonApp.sol"; ///@title Space aragon app smart contract ///@author Coinsence blockchain team contract Space is AragonApp { event NewMember(address member); event RemovedMember(address member); bytes32 public constant SPACE_MANAGER_ROLE = keccak256("SPACE_MANAGER_ROLE"); bytes32 public constant ADD_MEMBER_ROLE = keccak256("ADD_MEMBER_ROLE"); bytes32 public constant REMOVE_MEMBER_ROLE = keccak256("REMOVE_MEMBER_ROLE"); ///@notice space name string public name; ///@notice space description bytes32 public descHash; ///@notice space owner address public owner; ///@notice space members address[] public members; ///@notice mapping to verifiy if address is a member in the space mapping(address => bool) public isMember; /** * @notice init space * @dev maybe using another function to set space parameters so we don't need to pass them later to the DAO * @param _name space name */ function initialize(string _name, bytes32 _descHash) public onlyInit { //set space parameters name = _name; owner = msg.sender; descHash = _descHash; //set space owner as member members.push(msg.sender); isMember[msg.sender] = true; initialized(); } /** * @notice get space members count * @return members number */ function getMembersCount() public view isInitialized returns (uint256) { return members.length; } /** * @notice add members to the space * @dev use this function to add members even if one member only (less functions) * @param _members list of members addresses */ function addMembers(address[] _members) public isInitialized auth(ADD_MEMBER_ROLE) { require(verifyMembers(_members), "invalid member address"); for (uint i = 0; i < _members.length; i++) { //only add addresses that are not already members if (isMember[_members[i]] != true) { isMember[_members[i]] = true; members.push(_members[i]); emit NewMember(_members[i]); } } } /** * @notice leave space * @dev not the best way to do that...we may remove the members array completely */ function leaveSpace() public isInitialized { require(isMember[msg.sender], "You are not a space member"); //get address position in members array uint256 memberPosition = getMemberAddressPosition(msg.sender); //delete address delete members[memberPosition]; //set as not member isMember[msg.sender] = false; emit RemovedMember(msg.sender); } /** * @notice remove user from space * @dev function can only be called by address that have REMOVE_MEMBER_ROLE * @param _member address of the member to remove */ function removeMember(address _member) public isInitialized auth(REMOVE_MEMBER_ROLE) { require((_member != msg.sender) && (_member != address(0)), "error"); require(isMember[_member], "Member does not exist"); //get address position in members array uint256 memberPosition = getMemberAddressPosition(_member); //delete address delete members[memberPosition]; //set as not member isMember[_member] = false; emit RemovedMember(_member); } /** * @notice verify members addresses * @dev maybe changing addresses verification in the front-end (less gas cost) * @param _members list of addresses * @return true if all addresses are valid, otherwise return false */ function verifyMembers(address[] _members) internal view returns(bool) { for (uint i = 0; i < _members.length; i++) { if ((_members[i] == address(0)) || (_members[i] == msg.sender)) { return false; } } return true; } /** * @notice set addresses as members * @param _members list of addresses */ function setAsMembers(address[] _members) internal onlyInit { for (uint i = 0; i < _members.length; i++) { isMember[_members[i]] = true; } } /** * @notice Get member address position from members array * @param _address member address * @return position */ function getMemberAddressPosition(address _address) internal view isInitialized returns (uint256) { require(isMember[_address], "member not found"); for (uint256 i = 0; i < members.length; i++) { if (members[i] == _address) { return i; } } } }
* @notice verify members addresses @dev maybe changing addresses verification in the front-end (less gas cost) @param _members list of addresses @return true if all addresses are valid, otherwise return false/
function verifyMembers(address[] _members) internal view returns(bool) { for (uint i = 0; i < _members.length; i++) { if ((_members[i] == address(0)) || (_members[i] == msg.sender)) { return false; } } return true; }
12,616,312
[ 1, 8705, 4833, 6138, 225, 6944, 12770, 6138, 11805, 316, 326, 6641, 17, 409, 261, 2656, 16189, 6991, 13, 225, 389, 7640, 666, 434, 6138, 327, 638, 309, 777, 6138, 854, 923, 16, 3541, 327, 629, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 3929, 6918, 12, 2867, 8526, 389, 7640, 13, 2713, 1476, 1135, 12, 6430, 13, 288, 203, 3639, 364, 261, 11890, 277, 273, 374, 31, 277, 411, 389, 7640, 18, 2469, 31, 277, 27245, 288, 203, 5411, 309, 14015, 67, 7640, 63, 77, 65, 422, 1758, 12, 20, 3719, 747, 261, 67, 7640, 63, 77, 65, 422, 1234, 18, 15330, 3719, 288, 203, 7734, 327, 629, 31, 203, 5411, 289, 203, 3639, 289, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/* ███████╗ ██████╗ ██╗ ██╗ ██████╗ █████╗ ███╗ ███╗███████╗ ██╔════╝██╔═══██╗╚██╗██╔╝ ██╔════╝ ██╔══██╗████╗ ████║██╔════╝ █████╗ ██║ ██║ ╚███╔╝ ██║ ███╗███████║██╔████╔██║█████╗ ██╔══╝ ██║ ██║ ██╔██╗ ██║ ██║██╔══██║██║╚██╔╝██║██╔══╝ ██║ ╚██████╔╝██╔╝ ██╗ ╚██████╔╝██║ ██║██║ ╚═╝ ██║███████╗ ╚═╝ ╚═════╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═╝╚══════╝ */ // SPDX-License-Identifier: MIT pragma solidity ^0.8.10; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721ReceiverUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/cryptography/ECDSAUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/structs/EnumerableSetUpgradeable.sol"; import "./IFoxGame.sol"; import "./IFoxGameCarrot.sol"; import "./IFoxGameCrown.sol"; import "./IFoxGameNFT.sol"; contract FoxGames_v3 is IFoxGame, OwnableUpgradeable, IERC721ReceiverUpgradeable, PausableUpgradeable, ReentrancyGuardUpgradeable { using ECDSAUpgradeable for bytes32; // signature verification helpers using EnumerableSetUpgradeable for EnumerableSetUpgradeable.UintSet; // iterable staked tokens /**** * Thanks for checking out our contracts. * If you're interested in working with us, you can find us on * discord (https://discord.gg/foxgame). We also have a bug bounty * program and are available at @officialfoxgame or [email protected] ***/ // Advantage score adjustments for both foxes and hunters uint8 public constant MAX_ADVANTAGE = 8; uint8 public constant MIN_ADVANTAGE = 5; // Foxes take a 40% tax on all rabbiot $CARROT claimed uint8 public constant RABBIT_CLAIM_TAX_PERCENTAGE = 40; // Hunters have a 5% chance of stealing a fox as it unstakes uint8 private hunterStealFoxProbabilityMod; // Cut between hunters and foxes uint8 private hunterTaxCutPercentage; // Total hunter marksman scores staked uint16 public totalMarksmanPointsStaked; // Total fox cunning scores staked uint16 public totalCunningPointsStaked; // Number of Rabbit staked uint32 public totalRabbitsStaked; // Number of Foxes staked uint32 public totalFoxesStaked; // Number of Hunters staked uint32 public totalHuntersStaked; // The last time $CARROT was claimed uint48 public lastClaimTimestamp; // Rabbits must have 2 days worth of $CARROT to unstake or else it's too cold uint48 public constant RABBIT_MINIMUM_TO_EXIT = 2 days; // There will only ever be (roughly) 2.5 billion $CARROT earned through staking uint128 public constant MAXIMUM_GLOBAL_CARROT = 2500000000 ether; // amount of $CARROT earned so far uint128 public totalCarrotEarned; // Collected rewards before any foxes staked uint128 public unaccountedFoxRewards; // Collected rewards before any foxes staked uint128 public unaccountedHunterRewards; // Amount of $CARROT due for each cunning point staked uint128 public carrotPerCunningPoint; // Amount of $CARROT due for each marksman point staked uint128 public carrotPerMarksmanPoint; // Rabbit earn 10000 $CARROT per day uint128 public constant RABBIT_EARNING_RATE = 115740740740740740; // 10000 ether / 1 days; // Hunters earn 20000 $CARROT per day uint128 public constant HUNTER_EARNING_RATE = 231481481481481470; // 20000 ether / 1 days; // Staking state for both time-based and point-based rewards struct TimeStake { uint16 tokenId; uint48 time; address owner; } struct EarningStake { uint16 tokenId; uint128 earningRate; address owner; } // Events event TokenStaked(string kind, uint16 tokenId, address owner); event TokenUnstaked(string kind, uint16 tokenId, address owner, uint128 earnings); event FoxStolen(uint16 foxTokenId, address thief, address victim); // Signature to prove membership and randomness address private signVerifier; // External contract reference IFoxGameNFT private foxNFT; IFoxGameCarrot private foxCarrot; // Staked rabbits mapping(uint16 => TimeStake) public rabbitStakeByToken; // Staked foxes mapping(uint8 => EarningStake[]) public foxStakeByCunning; // foxes grouped by cunning mapping(uint16 => uint16) public foxHierarchy; // fox location within cunning group // Staked hunters mapping(uint16 => TimeStake) public hunterStakeByToken; mapping(uint8 => EarningStake[]) public hunterStakeByMarksman; // hunter grouped by markman mapping(uint16 => uint16) public hunterHierarchy; // hunter location within marksman group // FoxGame membership date mapping(address => uint48) public membershipDate; mapping(address => uint32) public memberNumber; event MemberJoined(address member, uint32 memberCount); uint32 public membershipCount; // External contract reference IFoxGameNFT private foxNFTGen1; // Mapping for staked tokens mapping(address => EnumerableSetUpgradeable.UintSet) private _stakedTokens; // Bool to store staking data bool private _storeStaking; // Use seed instead uint256 private _seed; // Reference to phase 2 utility token IFoxGameCrown private foxCrown; // amount of $CROWN earned so far uint128 public totalCrownEarned; // Cap CROWN earnings after 2.5 billion has been distributed uint128 public constant MAXIMUM_GLOBAL_CROWN = 2500000000 ether; // Entropy storage for future events that require randomness (claim, unstake). // Address => OP (claim/unstake) => TokenID => BlockNumber mapping(address => mapping(uint8 => mapping(uint16 => uint32))) private _stakeClaimBlock; // Op keys for Entropy storage uint8 private constant UNSTAKE_AND_CLAIM_IDX = 0; uint8 private constant CLAIM_IDX = 1; // Cost of a barrel in CARROT uint256 public barrelPrice; // Track account purchase of barrels mapping(address => uint48) private barrelPurchaseDate; // Barrel event purchase event BarrelPurchase(address account, uint256 price, uint48 timestamp); // Date when corruption begins to spread... 2 things happen: // 1. Carrot begins to burning // 2. Game risks go up uint48 public corruptionStartDate; // The last time $CROWN was claimed uint48 public lastCrownClaimTimestamp; // Phase 2 start date with 3 meanings: // - the date carrot will no long accrue rewards // - the date crown will start acruing rewards // - the start of a 24-hour countdown for corruption uint48 public divergenceTime; // Corruption percent rate per second uint128 public constant CORRUPTION_BURN_PERCENT_RATE = 1157407407407; // 10% burned per day // Events for token claiming in phase 2 event ClaimCarrot(IFoxGameNFT.Kind, uint16 tokenId, address owner, uint128 reward, uint128 corruptedCarrot); event CrownClaimed(string kind, uint16 tokenId, address owner, bool unstake, uint128 reward, uint128 tax, bool elevatedRisk); // Store a bool per token to ensure we dont double claim carrot mapping(uint16 => bool) private tokenCarrotClaimed; // < Placeholder > uint48 private ___; // Amount of $CROWN due for each cunning point staked uint128 public crownPerCunningPoint; // Amount of $CROWN due for each marksman point staked uint128 public crownPerMarksmanPoint; // Indicator of which users are still grandfathered into the ground floor of // $CROWN earnings. mapping(uint16 => bool) private hasRecentEarningPoint; /** * Set the date for phase 2 launch. * @param timestamp Timestamp */ function setDivergenceTime(uint48 timestamp) external onlyOwner { divergenceTime = timestamp; } /** * Init contract upgradability (only called once). */ function initialize() public initializer { __Ownable_init(); __ReentrancyGuard_init(); __Pausable_init(); hunterStealFoxProbabilityMod = 20; // 100/5=20 hunterTaxCutPercentage = 30; // whole number % // Pause staking on init _pause(); } /** * Returns the corruption start date. */ function getCorruptionEnabled() external view returns (bool) { return corruptionStartDate != 0 && corruptionStartDate < block.timestamp; } /** * Sets the date when corruption will begin to destroy carrot. * @param timestamp time. */ function setCorruptionStartTime(uint48 timestamp) external onlyOwner { corruptionStartDate = timestamp; } /** * Helper functions for validating random seeds. */ function getClaimSigningHash(address recipient, uint16[] calldata tokenIds, bool unstake, uint32[] calldata blocknums, uint256[] calldata seeds) public pure returns (bytes32) { return keccak256(abi.encodePacked(recipient, tokenIds, unstake, blocknums, seeds)); } function getMintSigningHash(address recipient, uint8 token, uint32 blocknum, uint256 seed) public pure returns (bytes32) { return keccak256(abi.encodePacked(recipient, token, blocknum, seed)); } function isValidMintSignature(address recipient, uint8 token, uint32 blocknum, uint256 seed, bytes memory sig) public view returns (bool) { bytes32 message = getMintSigningHash(recipient, token, blocknum, seed).toEthSignedMessageHash(); return ECDSAUpgradeable.recover(message, sig) == signVerifier; } function isValidClaimSignature(address recipient, uint16[] calldata tokenIds, bool unstake, uint32[] calldata blocknums, uint256[] calldata seeds, bytes memory sig) public view returns (bool) { bytes32 message = getClaimSigningHash(recipient, tokenIds, unstake, blocknums, seeds).toEthSignedMessageHash(); return ECDSAUpgradeable.recover(message, sig) == signVerifier; } /** * Set the purchase price of Barrels. * @param price Cost in CARROT */ function setBarrelPrice(uint256 price) external onlyOwner { barrelPrice = price; } /** * Allow accounts to purchase barrels using CARROT. */ function purchaseBarrel() external nonReentrant { require(tx.origin == msg.sender, "eos"); require(barrelPurchaseDate[msg.sender] == 0, "one barrel per account"); barrelPurchaseDate[msg.sender] = uint48(block.timestamp); foxCarrot.burn(msg.sender, barrelPrice); emit BarrelPurchase(msg.sender, barrelPrice, uint48(block.timestamp)); } /** * Exposes user barrel purchase date. * @param account Account to query. */ function ownsBarrel(address account) external view returns (bool) { return barrelPurchaseDate[account] != 0; } /** * Return the appropriate contract interface for token. */ function getTokenContract(uint16 tokenId) private view returns (IFoxGameNFT) { return tokenId <= 10000 ? foxNFT : foxNFTGen1; } /** * Helper method to fetch rotating entropy used to generate random seeds off-chain. * @param tokenIds List of token IDs. * @return entropies List of stored blocks per token. */ function getEntropies(address recipient, uint16[] calldata tokenIds) external view returns (uint32[2][] memory entropies) { require(tx.origin == msg.sender, "eos"); entropies = new uint32[2][](tokenIds.length); for (uint8 i; i < tokenIds.length; i++) { uint16 tokenId = tokenIds[i]; entropies[i] = [ _stakeClaimBlock[recipient][UNSTAKE_AND_CLAIM_IDX][tokenId], _stakeClaimBlock[recipient][CLAIM_IDX][tokenId] ]; } } /** * Adds Rabbits, Foxes and Hunters to their respective safe homes. * @param account the address of the staker * @param tokenIds the IDs of the Rabbit and Foxes to stake */ function stakeTokens(address account, uint16[] calldata tokenIds) external nonReentrant _updateEarnings { require((account == msg.sender && tx.origin == msg.sender) || msg.sender == address(foxNFTGen1), "not approved"); IFoxGameNFT nftContract; uint32 blocknum = uint32(block.number); mapping(uint16 => uint32) storage senderUnstakeBlock = _stakeClaimBlock[msg.sender][UNSTAKE_AND_CLAIM_IDX]; for (uint16 i; i < tokenIds.length; i++) { uint16 tokenId = tokenIds[i]; // Thieves abound and leave minting gaps if (tokenId == 0) { continue; } // Set unstake entropy senderUnstakeBlock[tokenId] = blocknum; // Add to respective safe homes nftContract = getTokenContract(tokenId); IFoxGameNFT.Kind kind = _getKind(nftContract, tokenId); if (kind == IFoxGameNFT.Kind.RABBIT) { _addRabbitToKeep(account, tokenId); } else if (kind == IFoxGameNFT.Kind.FOX) { _addFoxToDen(nftContract, account, tokenId); } else { // HUNTER _addHunterToCabin(nftContract, account, tokenId); } // Transfer into safe house if (msg.sender != address(foxNFTGen1)) { // dont do this step if its a mint + stake require(nftContract.ownerOf(tokenId) == msg.sender, "not owner"); nftContract.transferFrom(msg.sender, address(this), tokenId); } } } /** * Adds Rabbit to the Keep. * @param account the address of the staker * @param tokenId the ID of the Rabbit to add to the Barn */ function _addRabbitToKeep(address account, uint16 tokenId) internal { rabbitStakeByToken[tokenId] = TimeStake({ owner: account, tokenId: tokenId, time: uint48(block.timestamp) }); totalRabbitsStaked += 1; emit TokenStaked("RABBIT", tokenId, account); } /** * Add Fox to the Den. * @param account the address of the staker * @param tokenId the ID of the Fox */ function _addFoxToDen(IFoxGameNFT nftContract, address account, uint16 tokenId) internal { uint8 cunningIndex = _getAdvantagePoints(nftContract, tokenId); totalCunningPointsStaked += cunningIndex; // Store fox by rating foxHierarchy[tokenId] = uint16(foxStakeByCunning[cunningIndex].length); // Add fox to their cunning group foxStakeByCunning[cunningIndex].push(EarningStake({ owner: account, tokenId: tokenId, earningRate: crownPerCunningPoint })); // Phase 2 - Mark earning point as valid hasRecentEarningPoint[tokenId] = true; totalFoxesStaked += 1; emit TokenStaked("FOX", tokenId, account); } /** * Adds Hunter to the Cabin. * @param account the address of the staker * @param tokenId the ID of the Hunter */ function _addHunterToCabin(IFoxGameNFT nftContract, address account, uint16 tokenId) internal { uint8 marksmanIndex = _getAdvantagePoints(nftContract, tokenId); totalMarksmanPointsStaked += marksmanIndex; // Store hunter by rating hunterHierarchy[tokenId] = uint16(hunterStakeByMarksman[marksmanIndex].length); // Add hunter to their marksman group hunterStakeByMarksman[marksmanIndex].push(EarningStake({ owner: account, tokenId: tokenId, earningRate: crownPerMarksmanPoint })); hunterStakeByToken[tokenId] = TimeStake({ owner: account, tokenId: tokenId, time: uint48(block.timestamp) }); // Phase 2 - Mark earning point as valid hasRecentEarningPoint[tokenId] = true; totalHuntersStaked += 1; emit TokenStaked("HUNTER", tokenId, account); } // NB: Param struct is a workaround for too many variables error struct Param { IFoxGameNFT nftContract; uint16 tokenId; bool unstake; uint256 seed; } /** * Realize $CARROT earnings and optionally unstake tokens. * @param tokenIds the IDs of the tokens to claim earnings from * @param unstake whether or not to unstake ALL of the tokens listed in tokenIds * @param blocknums list of blocks each token previously was staked or claimed. * @param seeds random (off-chain) seeds provided for one-time use. * @param sig signature verification. */ function claimRewardsAndUnstake(bool unstake, uint16[] calldata tokenIds, uint32[] calldata blocknums, uint256[] calldata seeds, bytes calldata sig) external nonReentrant _updateEarnings { require(tx.origin == msg.sender, "eos"); require(isValidClaimSignature(msg.sender, tokenIds, unstake, blocknums, seeds, sig), "invalid signature"); require(tokenIds.length == blocknums.length && blocknums.length == seeds.length, "seed mismatch"); // Risk factors bool elevatedRisk = (corruptionStartDate != 0 && corruptionStartDate < block.timestamp) && // corrupted (barrelPurchaseDate[msg.sender] == 0); // does not have barrel // Calculate rewards for each token uint128 reward; mapping(uint16 => uint32) storage senderBlocks = _stakeClaimBlock[msg.sender][unstake ? UNSTAKE_AND_CLAIM_IDX : CLAIM_IDX]; Param memory params; for (uint8 i; i < tokenIds.length; i++) { uint16 tokenId = tokenIds[i]; // Confirm previous block matches seed generation require(senderBlocks[tokenId] == blocknums[i], "seed not match"); // Set new entropy for next claim (dont bother if unstaking) if (!unstake) { senderBlocks[tokenId] = uint32(block.number); } // NB: Param struct is a workaround for too many variables params.nftContract = getTokenContract(tokenId); params.tokenId = tokenId; params.unstake = unstake; params.seed = seeds[i]; IFoxGameNFT.Kind kind = _getKind(params.nftContract, params.tokenId); if (kind == IFoxGameNFT.Kind.RABBIT) { reward += _claimRabbitsFromKeep(params.nftContract, params.tokenId, params.unstake, params.seed, elevatedRisk); } else if (kind == IFoxGameNFT.Kind.FOX) { reward += _claimFoxFromDen(params.nftContract, params.tokenId, params.unstake, params.seed, elevatedRisk); } else { // HUNTER reward += _claimHunterFromCabin(params.nftContract, params.tokenId, params.unstake); } } // Disburse rewards if (reward != 0) { foxCrown.mint(msg.sender, reward); } } /** * realize $CARROT earnings for a single Rabbit and optionally unstake it * if not unstaking, pay a 20% tax to the staked foxes * if unstaking, there is a 50% chance all $CARROT is stolen * @param nftContract Contract belonging to the token * @param tokenId the ID of the Rabbit to claim earnings from * @param unstake whether or not to unstake the Rabbit * @param seed account seed * @param elevatedRisk true if the user is facing higher risk of losing their token * @return reward - the amount of $CARROT earned */ function _claimRabbitsFromKeep(IFoxGameNFT nftContract, uint16 tokenId, bool unstake, uint256 seed, bool elevatedRisk) internal returns (uint128 reward) { TimeStake storage stake = rabbitStakeByToken[tokenId]; require(stake.owner == msg.sender, "not owner"); uint48 time = uint48(block.timestamp); uint48 stakeStart = stake.time < divergenceTime ? divergenceTime : stake.time; // phase 2 reset require(!(unstake && time - stakeStart < RABBIT_MINIMUM_TO_EXIT), "needs 2 days of crown"); // $CROWN time-based rewards if (totalCrownEarned < MAXIMUM_GLOBAL_CROWN) { reward = (time - stakeStart) * RABBIT_EARNING_RATE; } else if (stakeStart <= lastCrownClaimTimestamp) { // stop earning additional $CROWN if it's all been earned reward = (lastCrownClaimTimestamp - stakeStart) * RABBIT_EARNING_RATE; } // Update reward based on game rules uint128 tax; if (unstake) { // Chance of all $CROWN stolen (normal=50% vs corrupted=75%) if (((seed >> 245) % 100) < (elevatedRisk ? 75 : 50)) { _payTaxToPredators(reward, true); tax = reward; reward = 0; } delete rabbitStakeByToken[tokenId]; totalRabbitsStaked -= 1; // send back Rabbit nftContract.safeTransferFrom(address(this), msg.sender, tokenId, ""); } else { // Pay foxes their tax tax = reward * RABBIT_CLAIM_TAX_PERCENTAGE / 100; _payTaxToPredators(tax, false); reward = reward * (100 - RABBIT_CLAIM_TAX_PERCENTAGE) / 100; // Update last earned time rabbitStakeByToken[tokenId] = TimeStake({ owner: msg.sender, tokenId: tokenId, time: time }); } emit CrownClaimed("RABBIT", tokenId, stake.owner, unstake, reward, tax, elevatedRisk); } /** * realize $CARROT earnings for a single Fox and optionally unstake it * foxes earn $CARROT proportional to their Alpha rank * @param nftContract Contract belonging to the token * @param tokenId the ID of the Fox to claim earnings from * @param unstake whether or not to unstake the Fox * @param seed account seed * @param elevatedRisk true if the user is facing higher risk of losing their token * @return reward - the amount of $CARROT earned */ function _claimFoxFromDen(IFoxGameNFT nftContract, uint16 tokenId, bool unstake, uint256 seed, bool elevatedRisk) internal returns (uint128 reward) { require(nftContract.ownerOf(tokenId) == address(this), "not staked"); uint8 cunningIndex = _getAdvantagePoints(nftContract, tokenId); EarningStake storage stake = foxStakeByCunning[cunningIndex][foxHierarchy[tokenId]]; require(stake.owner == msg.sender, "not owner"); // Calculate advantage-based rewards uint128 migratedEarningPoint = hasRecentEarningPoint[tokenId] ? stake.earningRate : 0; // phase 2 reset if (crownPerCunningPoint > migratedEarningPoint) { reward = (MAX_ADVANTAGE - cunningIndex + MIN_ADVANTAGE) * (crownPerCunningPoint - migratedEarningPoint); } if (unstake) { totalCunningPointsStaked -= cunningIndex; // Remove Alpha from total staked EarningStake storage lastStake = foxStakeByCunning[cunningIndex][foxStakeByCunning[cunningIndex].length - 1]; foxStakeByCunning[cunningIndex][foxHierarchy[tokenId]] = lastStake; // Shuffle last Fox to current position foxHierarchy[lastStake.tokenId] = foxHierarchy[tokenId]; foxStakeByCunning[cunningIndex].pop(); // Remove duplicate delete foxHierarchy[tokenId]; // Delete old mapping totalFoxesStaked -= 1; // Determine if Fox should be stolen by hunter (normal=5% vs corrupted=20%) address recipient = msg.sender; if (((seed >> 245) % (elevatedRisk ? 5 : hunterStealFoxProbabilityMod)) == 0) { recipient = _randomHunterOwner(seed); if (recipient == address(0x0)) { recipient = msg.sender; } else if (recipient != msg.sender) { emit FoxStolen(tokenId, recipient, msg.sender); } } nftContract.safeTransferFrom(address(this), recipient, tokenId, ""); } else { // Update earning point foxStakeByCunning[cunningIndex][foxHierarchy[tokenId]] = EarningStake({ owner: msg.sender, tokenId: tokenId, earningRate: crownPerCunningPoint }); hasRecentEarningPoint[tokenId] = true; } emit CrownClaimed("FOX", tokenId, stake.owner, unstake, reward, 0, elevatedRisk); } /** * realize $CARROT earnings for a single Fox and optionally unstake it * foxes earn $CARROT proportional to their Alpha rank * @param nftContract Contract belonging to the token * @param tokenId the ID of the Fox to claim earnings from * @param unstake whether or not to unstake the Fox * @return reward - the amount of $CARROT earned */ function _claimHunterFromCabin(IFoxGameNFT nftContract, uint16 tokenId, bool unstake) internal returns (uint128 reward) { require(foxNFTGen1.ownerOf(tokenId) == address(this), "not staked"); uint8 marksmanIndex = _getAdvantagePoints(nftContract, tokenId); EarningStake storage earningStake = hunterStakeByMarksman[marksmanIndex][hunterHierarchy[tokenId]]; require(earningStake.owner == msg.sender, "not owner"); uint48 time = uint48(block.timestamp); // Calculate advantage-based rewards uint128 migratedEarningPoint = hasRecentEarningPoint[tokenId] ? earningStake.earningRate : 0; // phase 2 reset if (crownPerMarksmanPoint > migratedEarningPoint) { reward = (MAX_ADVANTAGE - marksmanIndex + MIN_ADVANTAGE) * (crownPerMarksmanPoint - migratedEarningPoint); } if (unstake) { totalMarksmanPointsStaked -= marksmanIndex; // Remove Alpha from total staked EarningStake storage lastStake = hunterStakeByMarksman[marksmanIndex][hunterStakeByMarksman[marksmanIndex].length - 1]; hunterStakeByMarksman[marksmanIndex][hunterHierarchy[tokenId]] = lastStake; // Shuffle last Fox to current position hunterHierarchy[lastStake.tokenId] = hunterHierarchy[tokenId]; hunterStakeByMarksman[marksmanIndex].pop(); // Remove duplicate delete hunterHierarchy[tokenId]; // Delete old mapping } else { // Update earning point hunterStakeByMarksman[marksmanIndex][hunterHierarchy[tokenId]] = EarningStake({ owner: msg.sender, tokenId: tokenId, earningRate: crownPerMarksmanPoint }); hasRecentEarningPoint[tokenId] = true; } // Calcuate time-based rewards TimeStake storage timeStake = hunterStakeByToken[tokenId]; require(timeStake.owner == msg.sender, "not owner"); uint48 stakeStart = timeStake.time < divergenceTime ? divergenceTime : timeStake.time; // phase 2 reset if (totalCrownEarned < MAXIMUM_GLOBAL_CROWN) { reward += (time - stakeStart) * HUNTER_EARNING_RATE; } else if (stakeStart <= lastCrownClaimTimestamp) { // stop earning additional $CARROT if it's all been earned reward += (lastCrownClaimTimestamp - stakeStart) * HUNTER_EARNING_RATE; } if (unstake) { delete hunterStakeByToken[tokenId]; totalHuntersStaked -= 1; // Unstake to owner foxNFTGen1.safeTransferFrom(address(this), msg.sender, tokenId, ""); } else { // Update last earned time hunterStakeByToken[tokenId] = TimeStake({ owner: msg.sender, tokenId: tokenId, time: time }); } emit CrownClaimed("HUNTER", tokenId, earningStake.owner, unstake, reward, 0, false); } // Struct to abstract away calculation of rewards from claiming rewards struct TokenReward { address owner; IFoxGameNFT.Kind kind; uint128 reward; uint128 corruptedCarrot; } /** * Realize $CARROT earnings. There's no risk nor tax involed other than corruption. * @param tokenId the token ID * @param time current time * @return claim reward information */ function getCarrotReward(uint16 tokenId, uint48 time) private view returns (TokenReward memory claim) { IFoxGameNFT nftContract = getTokenContract(tokenId); claim.kind = _getKind(nftContract, tokenId); if (claim.kind == IFoxGameNFT.Kind.RABBIT) { claim = _getCarrotForRabbit(tokenId, time); } else if (claim.kind == IFoxGameNFT.Kind.FOX) { claim = _getCarrotForFox(nftContract, tokenId, time); } else { // HUNTER claim = _getCarrotForHunter(nftContract, tokenId, time); } } /** * Calculate carrot rewards for the given tokens. * @param tokenIds list of tokens * @return claims list of reward objects */ function getCarrotRewards(uint16[] calldata tokenIds) external view returns (TokenReward[] memory claims) { uint48 time = uint48(block.timestamp); claims = new TokenReward[](tokenIds.length); for (uint8 i; i < tokenIds.length; i++) { if (!tokenCarrotClaimed[tokenIds[i]]) { claims[i] = getCarrotReward(tokenIds[i], time); } } } /** * Realize $CARROT earnings. There's no risk nor tax involed other than corruption. * @param tokenIds the IDs of the tokens to claim earnings from */ function claimCarrotRewards(uint16[] calldata tokenIds) external { require(tx.origin == msg.sender, "eos"); uint128 reward; TokenReward memory claim; uint48 time = uint48(block.timestamp); for (uint8 i; i < tokenIds.length; i++) { if (!tokenCarrotClaimed[tokenIds[i]]) { claim = getCarrotReward(tokenIds[i], time); require(claim.owner == msg.sender, "not owner"); reward += claim.reward; emit ClaimCarrot(claim.kind, tokenIds[i], claim.owner, claim.reward, claim.corruptedCarrot); tokenCarrotClaimed[tokenIds[i]] = true; } } // Disburse rewards if (reward != 0) { foxCarrot.mint(msg.sender, reward); } } /** * Calculate the carrot accumulated per token. * @param time current time */ function calculateCorruptedCarrot(address account, uint128 reward, uint48 time) private view returns (uint128 corruptedCarrot) { // If user has rewards and corruption has started if (reward > 0 && corruptionStartDate != 0 && time > corruptionStartDate) { // Calulate time that corruption was in effect uint48 barrelTime = barrelPurchaseDate[account]; uint128 unsafeElapsed = (barrelTime == 0 ? time - corruptionStartDate // never bought barrel : barrelTime > corruptionStartDate ? barrelTime - corruptionStartDate // bought after corruption : 0 // bought before corruption ); // Subtract from reward if (unsafeElapsed > 0) { corruptedCarrot = uint128((reward * unsafeElapsed * uint256(CORRUPTION_BURN_PERCENT_RATE)) / 1000000000000000000 /* 1eth */); } } } /** * Realize $CARROT earnings for a single Rabbit * @param tokenId the ID of the Rabbit to claim earnings from * @param time current time * @return claim carrot claim object */ function _getCarrotForRabbit(uint16 tokenId, uint48 time) private view returns (TokenReward memory claim) { // Carrot time-based rewards uint128 reward; TimeStake storage stake = rabbitStakeByToken[tokenId]; if (divergenceTime == 0 || time < divergenceTime) { // divergence has't yet started reward = (time - stake.time) * RABBIT_EARNING_RATE; } else if (stake.time < divergenceTime) { // last moment to accrue carrot reward = (divergenceTime - stake.time) * RABBIT_EARNING_RATE; } claim.corruptedCarrot = calculateCorruptedCarrot(msg.sender, reward, time); claim.reward = reward - claim.corruptedCarrot; claim.owner = stake.owner; } /** * Realize $CARROT earnings for a single Fox * @param nftContract Contract belonging to the token * @param tokenId the ID of the Fox to claim earnings from * @param time current time * @return claim carrot claim object */ function _getCarrotForFox(IFoxGameNFT nftContract, uint16 tokenId, uint48 time) private view returns (TokenReward memory claim) { uint8 cunningIndex = _getAdvantagePoints(nftContract, tokenId); EarningStake storage stake = foxStakeByCunning[cunningIndex][foxHierarchy[tokenId]]; // Calculate advantage-based rewards uint128 reward; if (!hasRecentEarningPoint[tokenId] && carrotPerCunningPoint > stake.earningRate) { reward = (MAX_ADVANTAGE - cunningIndex + MIN_ADVANTAGE) * (carrotPerCunningPoint - stake.earningRate); } // Remove corrupted carrot claim.corruptedCarrot = calculateCorruptedCarrot(msg.sender, reward, time); claim.reward = reward - claim.corruptedCarrot; claim.owner = stake.owner; } /** * Realize $CARROT earnings for a single hunter * @param nftContract Contract belonging to the token * @param tokenId the ID of the Fox to claim earnings from * @param time current time * @return claim carrot claim object */ function _getCarrotForHunter(IFoxGameNFT nftContract, uint16 tokenId, uint48 time) private view returns (TokenReward memory claim) { require(foxNFTGen1.ownerOf(tokenId) == address(this), "not staked"); uint8 marksman = _getAdvantagePoints(nftContract, tokenId); EarningStake storage earningStake = hunterStakeByMarksman[marksman][hunterHierarchy[tokenId]]; require(earningStake.owner == msg.sender, "not owner"); // Calculate advantage-based rewards uint128 reward; if (!hasRecentEarningPoint[tokenId] && carrotPerMarksmanPoint > earningStake.earningRate) { reward = marksman * (carrotPerMarksmanPoint - earningStake.earningRate); } // Carrot time-based rewards TimeStake storage timeStake = hunterStakeByToken[tokenId]; if (divergenceTime == 0 || time < divergenceTime) { reward += (time - timeStake.time) * HUNTER_EARNING_RATE; } else if (timeStake.time < divergenceTime) { reward += (divergenceTime - timeStake.time) * HUNTER_EARNING_RATE; } // Remove corrupted carrot claim.corruptedCarrot = calculateCorruptedCarrot(msg.sender, reward, time); claim.reward = reward - claim.corruptedCarrot; claim.owner = earningStake.owner; } /** * Add $CARROT claimable pots for hunters and foxes * @param amount $CARROT to add to the pot * @param includeHunters true if hunters take a cut of the spoils */ function _payTaxToPredators(uint128 amount, bool includeHunters) internal { uint128 amountDueFoxes = amount; // Hunters take their cut first if (includeHunters) { uint128 amountDueHunters = amount * hunterTaxCutPercentage / 100; amountDueFoxes -= amountDueHunters; // Update hunter pools if (totalMarksmanPointsStaked == 0) { unaccountedHunterRewards += amountDueHunters; } else { crownPerMarksmanPoint += (amountDueHunters + unaccountedHunterRewards) / totalMarksmanPointsStaked; unaccountedHunterRewards = 0; } } // Update fox pools if (totalCunningPointsStaked == 0) { unaccountedFoxRewards += amountDueFoxes; } else { // makes sure to include any unaccounted $CARROT crownPerCunningPoint += (amountDueFoxes + unaccountedFoxRewards) / totalCunningPointsStaked; unaccountedFoxRewards = 0; } } /** * Tracks $CARROT earnings to ensure it stops once 2.4 billion is eclipsed */ modifier _updateEarnings() { uint48 time = uint48(block.timestamp); // CROWN - Capped by supply if (totalCrownEarned < MAXIMUM_GLOBAL_CROWN) { uint48 elapsed = time - lastCrownClaimTimestamp; totalCrownEarned += (elapsed * totalRabbitsStaked * RABBIT_EARNING_RATE) + (elapsed * totalHuntersStaked * HUNTER_EARNING_RATE); lastCrownClaimTimestamp = time; } _; } /** * Get token kind (rabbit, fox, hunter) * @param tokenId the ID of the token to check * @return kind */ function _getKind(IFoxGameNFT nftContract, uint16 tokenId) internal view returns (IFoxGameNFT.Kind) { return nftContract.getTraits(tokenId).kind; } /** * gets the alpha score for a Fox * @param tokenId the ID of the Fox to get the alpha score for * @return the alpha score of the Fox (5-8) */ function _getAdvantagePoints(IFoxGameNFT nftContract, uint16 tokenId) internal view returns (uint8) { return MAX_ADVANTAGE - nftContract.getTraits(tokenId).advantage; // alpha index is 0-3 } /** * chooses a random Fox thief when a newly minted token is stolen * @param seed a random value to choose a Fox from * @return the owner of the randomly selected Fox thief */ function randomFoxOwner(uint256 seed) external view returns (address) { if (totalCunningPointsStaked == 0) { return address(0x0); // use 0x0 to return to msg.sender } // choose a value from 0 to total alpha staked uint256 bucket = (seed & 0xFFFFFFFF) % totalCunningPointsStaked; uint256 cumulative; seed >>= 32; // loop through each cunning bucket of Foxes for (uint8 i = MAX_ADVANTAGE - 3; i <= MAX_ADVANTAGE; i++) { cumulative += foxStakeByCunning[i].length * i; // if the value is not inside of that bucket, keep going if (bucket >= cumulative) continue; // get the address of a random Fox with that alpha score return foxStakeByCunning[i][seed % foxStakeByCunning[i].length].owner; } return address(0x0); } /** * Chooses a random Hunter to steal a fox. * @param seed a random value to choose a Hunter from * @return the owner of the randomly selected Hunter thief */ function _randomHunterOwner(uint256 seed) internal view returns (address) { if (totalMarksmanPointsStaked == 0) { return address(0x0); // use 0x0 to return to msg.sender } // choose a value from 0 to total alpha staked uint256 bucket = (seed & 0xFFFFFFFF) % totalMarksmanPointsStaked; uint256 cumulative; seed >>= 32; // loop through each cunning bucket of Foxes for (uint8 i = MAX_ADVANTAGE - 3; i <= MAX_ADVANTAGE; i++) { cumulative += hunterStakeByMarksman[i].length * i; // if the value is not inside of that bucket, keep going if (bucket >= cumulative) continue; // get the address of a random Fox with that alpha score return hunterStakeByMarksman[i][seed % hunterStakeByMarksman[i].length].owner; } return address(0x0); } /** * Realize $CROWN earnings * @param tokenIds the IDs of the tokens to claim earnings from */ function calculateRewards(uint16[] calldata tokenIds) external view returns (TokenReward[] memory tokenRewards) { require(tx.origin == msg.sender, "eos only"); IFoxGameNFT.Kind kind; IFoxGameNFT nftContract; tokenRewards = new TokenReward[](tokenIds.length); uint48 time = uint48(block.timestamp); for (uint8 i = 0; i < tokenIds.length; i++) { nftContract = getTokenContract(tokenIds[i]); kind = _getKind(nftContract, tokenIds[i]); if (kind == IFoxGameNFT.Kind.RABBIT) { tokenRewards[i] = _calculateRabbitReward(tokenIds[i], time); } else if (kind == IFoxGameNFT.Kind.FOX) { tokenRewards[i] = _calculateFoxReward(nftContract, tokenIds[i]); } else { // HUNTER tokenRewards[i] = _calculateHunterReward(nftContract, tokenIds[i], time); } } } /** * Calculate rabbit reward. * @param tokenId the ID of the Rabbit to claim earnings from * @param time currnet block time * @return tokenReward token reward response */ function _calculateRabbitReward(uint16 tokenId, uint48 time) internal view returns (TokenReward memory tokenReward) { TimeStake storage stake = rabbitStakeByToken[tokenId]; uint48 stakeStart = stake.time < divergenceTime ? divergenceTime : stake.time; // phase 2 reset // Calcuate time-based rewards uint128 reward; if (totalCrownEarned < MAXIMUM_GLOBAL_CROWN) { reward = (time - stakeStart) * RABBIT_EARNING_RATE; } else if (stakeStart <= lastCrownClaimTimestamp) { // stop earning additional $CROWN if it's all been earned reward = (lastCrownClaimTimestamp - stakeStart) * RABBIT_EARNING_RATE; } // Compose reward object tokenReward.owner = stake.owner; tokenReward.reward = reward * (100 - RABBIT_CLAIM_TAX_PERCENTAGE) / 100; } /** * Calculate fox reward. * @param nftContract Contract belonging to the token * @param tokenId the ID of the Fox to claim earnings from * @return tokenReward token reward response */ function _calculateFoxReward(IFoxGameNFT nftContract, uint16 tokenId) internal view returns (TokenReward memory tokenReward) { uint8 cunningIndex = _getAdvantagePoints(nftContract, tokenId); EarningStake storage stake = foxStakeByCunning[cunningIndex][foxHierarchy[tokenId]]; // Calculate advantage-based rewards uint128 reward; uint128 migratedEarningPoint = hasRecentEarningPoint[tokenId] ? stake.earningRate : 0; // phase 2 reset if (crownPerCunningPoint > migratedEarningPoint) { reward = (MAX_ADVANTAGE - cunningIndex + MIN_ADVANTAGE) * (crownPerCunningPoint - migratedEarningPoint); } // Compose reward object tokenReward.owner = stake.owner; tokenReward.reward = reward; } /** * Calculate hunter reward. * @param nftContract Contract belonging to the token * @param tokenId the ID of the Fox to claim earnings from * @param time currnet block time * @return tokenReward token reward response */ function _calculateHunterReward(IFoxGameNFT nftContract, uint16 tokenId, uint48 time) internal view returns (TokenReward memory tokenReward) { uint8 marksmanIndex = _getAdvantagePoints(nftContract, tokenId); EarningStake storage earningStake = hunterStakeByMarksman[marksmanIndex][hunterHierarchy[tokenId]]; // Calculate advantage-based rewards uint128 reward; uint128 migratedEarningPoint = hasRecentEarningPoint[tokenId] ? earningStake.earningRate : 0; // phase 2 reset if (crownPerMarksmanPoint > migratedEarningPoint) { reward = (MAX_ADVANTAGE - marksmanIndex + MIN_ADVANTAGE) * (crownPerMarksmanPoint - migratedEarningPoint); } // Calcuate time-based rewards TimeStake storage timeStake = hunterStakeByToken[tokenId]; uint48 stakeStart = timeStake.time < divergenceTime ? divergenceTime : timeStake.time; // phase 2 reset require(timeStake.owner == msg.sender, "not owner"); if (totalCrownEarned < MAXIMUM_GLOBAL_CROWN) { reward += (time - stakeStart) * HUNTER_EARNING_RATE; } else if (stakeStart <= lastCrownClaimTimestamp) { reward += (lastCrownClaimTimestamp - stakeStart) * HUNTER_EARNING_RATE; } // Compose reward object tokenReward.owner = earningStake.owner; tokenReward.reward = reward; } /** * Interface support to allow player staking. */ function onERC721Received(address, address from, uint256, bytes calldata) external pure override returns (bytes4) { require(from == address(0x0)); return IERC721ReceiverUpgradeable.onERC721Received.selector; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { _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); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract PausableUpgradeable is Initializable, ContextUpgradeable { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ function __Pausable_init() internal initializer { __Context_init_unchained(); __Pausable_init_unchained(); } function __Pausable_init_unchained() internal initializer { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.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; /** * @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; /** * @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 ECDSAUpgradeable { 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 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)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSetUpgradeable { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping(bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; if (lastIndex != toDeleteIndex) { bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex } // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { return set._values[index]; } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function _values(Set storage set) private view returns (bytes32[] memory) { return set._values; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(Bytes32Set storage set) internal view returns (bytes32[] memory) { return _values(set._inner); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(AddressSet storage set) internal view returns (address[] memory) { bytes32[] memory store = _values(set._inner); address[] memory result; assembly { result := store } return result; } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(UintSet storage set) internal view returns (uint256[] memory) { bytes32[] memory store = _values(set._inner); uint256[] memory result; assembly { result := store } return result; } } /* ███████╗ ██████╗ ██╗ ██╗ ██████╗ █████╗ ███╗ ███╗███████╗ ██╔════╝██╔═══██╗╚██╗██╔╝ ██╔════╝ ██╔══██╗████╗ ████║██╔════╝ █████╗ ██║ ██║ ╚███╔╝ ██║ ███╗███████║██╔████╔██║█████╗ ██╔══╝ ██║ ██║ ██╔██╗ ██║ ██║██╔══██║██║╚██╔╝██║██╔══╝ ██║ ╚██████╔╝██╔╝ ██╗ ╚██████╔╝██║ ██║██║ ╚═╝ ██║███████╗ ╚═╝ ╚═════╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═╝╚══════╝ */ // SPDX-License-Identifier: MIT pragma solidity ^0.8.10; interface IFoxGame { function stakeTokens(address, uint16[] calldata) external; function randomFoxOwner(uint256) external view returns (address); function isValidMintSignature(address, uint8, uint32, uint256, bytes memory) external view returns (bool); function ownsBarrel(address) external view returns (bool); function getCorruptionEnabled() external view returns (bool); } /* ███████╗ ██████╗ ██╗ ██╗ ██████╗ █████╗ ███╗ ███╗███████╗ ██╔════╝██╔═══██╗╚██╗██╔╝ ██╔════╝ ██╔══██╗████╗ ████║██╔════╝ █████╗ ██║ ██║ ╚███╔╝ ██║ ███╗███████║██╔████╔██║█████╗ ██╔══╝ ██║ ██║ ██╔██╗ ██║ ██║██╔══██║██║╚██╔╝██║██╔══╝ ██║ ╚██████╔╝██╔╝ ██╗ ╚██████╔╝██║ ██║██║ ╚═╝ ██║███████╗ ╚═╝ ╚═════╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═╝╚══════╝ */ // SPDX-License-Identifier: MIT pragma solidity ^0.8.10; interface IFoxGameCarrot { function mint(address to, uint256 amount) external; function burn(address from, uint256 amount) external; } /* ███████╗ ██████╗ ██╗ ██╗ ██████╗ █████╗ ███╗ ███╗███████╗ ██╔════╝██╔═══██╗╚██╗██╔╝ ██╔════╝ ██╔══██╗████╗ ████║██╔════╝ █████╗ ██║ ██║ ╚███╔╝ ██║ ███╗███████║██╔████╔██║█████╗ ██╔══╝ ██║ ██║ ██╔██╗ ██║ ██║██╔══██║██║╚██╔╝██║██╔══╝ ██║ ╚██████╔╝██╔╝ ██╗ ╚██████╔╝██║ ██║██║ ╚═╝ ██║███████╗ ╚═╝ ╚═════╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═╝╚══════╝ */ // SPDX-License-Identifier: MIT pragma solidity ^0.8.10; interface IFoxGameCrown { function mint(address to, uint256 amount) external; function burn(address from, uint256 amount) external; } /* ███████╗ ██████╗ ██╗ ██╗ ██████╗ █████╗ ███╗ ███╗███████╗ ██╔════╝██╔═══██╗╚██╗██╔╝ ██╔════╝ ██╔══██╗████╗ ████║██╔════╝ █████╗ ██║ ██║ ╚███╔╝ ██║ ███╗███████║██╔████╔██║█████╗ ██╔══╝ ██║ ██║ ██╔██╗ ██║ ██║██╔══██║██║╚██╔╝██║██╔══╝ ██║ ╚██████╔╝██╔╝ ██╗ ╚██████╔╝██║ ██║██║ ╚═╝ ██║███████╗ ╚═╝ ╚═════╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═╝╚══════╝ */ // SPDX-License-Identifier: MIT pragma solidity ^0.8.10; interface IFoxGameNFT { enum Kind { RABBIT, FOX, HUNTER } enum Coin { CARROT, CROWN } struct Traits { Kind kind; uint8 advantage; uint8[7] traits; } function getMaxGEN0Players() external pure returns (uint16); function getTraits(uint16) external view returns (Traits memory); function ownerOf(uint256) external view returns (address owner); function transferFrom(address, address, uint256) external; function safeTransferFrom(address, address, uint256, bytes memory) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev 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; } } }
Confirm previous block matches seed generation Set new entropy for next claim (dont bother if unstaking)
for (uint8 i; i < tokenIds.length; i++) { uint16 tokenId = tokenIds[i]; require(senderBlocks[tokenId] == blocknums[i], "seed not match"); if (!unstake) { senderBlocks[tokenId] = uint32(block.number); } params.tokenId = tokenId; params.unstake = unstake; params.seed = seeds[i]; IFoxGameNFT.Kind kind = _getKind(params.nftContract, params.tokenId); if (kind == IFoxGameNFT.Kind.RABBIT) { reward += _claimRabbitsFromKeep(params.nftContract, params.tokenId, params.unstake, params.seed, elevatedRisk); reward += _claimFoxFromDen(params.nftContract, params.tokenId, params.unstake, params.seed, elevatedRisk); reward += _claimHunterFromCabin(params.nftContract, params.tokenId, params.unstake); } }
14,423,379
[ 1, 11269, 2416, 1203, 1885, 5009, 9377, 1000, 394, 15943, 364, 1024, 7516, 261, 72, 1580, 23440, 309, 640, 334, 6159, 13, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 364, 261, 11890, 28, 277, 31, 277, 411, 1147, 2673, 18, 2469, 31, 277, 27245, 288, 203, 1377, 2254, 2313, 1147, 548, 273, 1147, 2673, 63, 77, 15533, 203, 203, 1377, 2583, 12, 15330, 6450, 63, 2316, 548, 65, 422, 1203, 21180, 63, 77, 6487, 315, 12407, 486, 845, 8863, 203, 203, 1377, 309, 16051, 23412, 911, 13, 288, 203, 3639, 5793, 6450, 63, 2316, 548, 65, 273, 2254, 1578, 12, 2629, 18, 2696, 1769, 203, 1377, 289, 203, 203, 1377, 859, 18, 2316, 548, 273, 1147, 548, 31, 203, 1377, 859, 18, 23412, 911, 273, 640, 334, 911, 31, 203, 1377, 859, 18, 12407, 273, 19076, 63, 77, 15533, 203, 203, 1377, 11083, 2409, 12496, 50, 4464, 18, 5677, 3846, 273, 389, 588, 5677, 12, 2010, 18, 82, 1222, 8924, 16, 859, 18, 2316, 548, 1769, 203, 1377, 309, 261, 9224, 422, 11083, 2409, 12496, 50, 4464, 18, 5677, 18, 54, 2090, 15650, 13, 288, 203, 3639, 19890, 1011, 389, 14784, 54, 378, 6789, 1265, 11523, 12, 2010, 18, 82, 1222, 8924, 16, 859, 18, 2316, 548, 16, 859, 18, 23412, 911, 16, 859, 18, 12407, 16, 30047, 690, 54, 10175, 1769, 203, 3639, 19890, 1011, 389, 14784, 42, 2409, 1265, 8517, 12, 2010, 18, 82, 1222, 8924, 16, 859, 18, 2316, 548, 16, 859, 18, 23412, 911, 16, 859, 18, 12407, 16, 30047, 690, 54, 10175, 1769, 203, 3639, 19890, 1011, 389, 14784, 44, 318, 387, 1265, 39, 378, 267, 12, 2010, 18, 82, 1222, 8924, 16, 859, 18, 2316, 548, 2 ]
./partial_match/42/0xdb71304030a282D7122b5f32db3b0292447F1304/sources/CFDState.sol
File: contracts/interface/ICFDState.sol
interface ICFDState { function getMMLiquidity(address _exchange) external view returns (SignedDecimal.signedDecimal memory); function getLatestCumulativePremiumFraction(IExchange _exchange) external view returns (SignedDecimal.signedDecimal memory); function getLatestCumulativeOvernightFeeRate(IExchange _exchange) external view returns (Decimal.decimal memory); } struct TradingState { uint256 lastestLongTime; uint256 lastestShortTime; } struct RemainMarginInfo { Decimal.decimal remainMargin; Decimal.decimal badDebt; SignedDecimal.signedDecimal fundingPayment; Decimal.decimal overnightFee; } }
3,386,793
[ 1, 812, 30, 20092, 19, 5831, 19, 2871, 16894, 1119, 18, 18281, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 5831, 467, 8955, 40, 1119, 288, 203, 565, 445, 2108, 1495, 18988, 24237, 12, 2867, 389, 16641, 13, 3903, 1476, 1135, 261, 12294, 5749, 18, 5679, 5749, 3778, 1769, 203, 203, 565, 445, 336, 18650, 39, 11276, 23890, 5077, 13724, 12, 45, 11688, 389, 16641, 13, 3903, 1476, 1135, 261, 12294, 5749, 18, 5679, 5749, 3778, 1769, 203, 203, 565, 445, 336, 18650, 39, 11276, 4851, 18840, 14667, 4727, 12, 45, 11688, 389, 16641, 13, 3903, 1476, 1135, 261, 5749, 18, 12586, 3778, 1769, 203, 97, 203, 203, 203, 203, 203, 203, 203, 565, 1958, 2197, 7459, 1119, 288, 203, 3639, 2254, 5034, 225, 1142, 395, 3708, 950, 31, 203, 3639, 2254, 5034, 225, 1142, 395, 4897, 950, 31, 203, 565, 289, 203, 203, 565, 1958, 2663, 530, 9524, 966, 288, 203, 3639, 11322, 18, 12586, 7232, 9524, 31, 203, 3639, 11322, 18, 12586, 5570, 758, 23602, 31, 203, 3639, 16724, 5749, 18, 5679, 5749, 22058, 6032, 31, 203, 3639, 11322, 18, 12586, 1879, 18840, 14667, 31, 203, 565, 289, 203, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: BSD-4-Clause pragma solidity 0.8.3; import "./IOddzLiquidityPool.sol"; import "../Libs/DateTimeLibrary.sol"; import "../Libs/ABDKMath64x64.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/Address.sol"; abstract contract AbstractOddzPool is Ownable, IOddzLiquidityPool { using Address for address; /** * @dev Liquidity specific data definitions */ uint256 public poolBalance; uint256 public lockedAmount; struct ProviderBalance { uint256 _amount; uint256 _date; uint256 _premiumAllocated; uint256 _lastPremiumCollected; bool _isNegativePremium; } mapping(address => ProviderBalance) public liquidityProvider; // To distribute loss in the pool mapping(uint256 => uint256) public daysActiveLiquidity; uint256 public latestLiquidityEvent; /** * @dev Premium specific data definitions */ struct PremiumPool { uint256 _collected; uint256 _exercised; uint256 _surplus; } mapping(uint256 => PremiumPool) public premiumDayPool; function getBalance(address _provider) external view override returns (uint256 amount) { amount = liquidityProvider[_provider]._amount; } /** * @notice Add liquidity for the day * @param _amount USD value * @param _provider Address of the Liquidity Provider */ function addLiquidity(uint256 _amount, address _provider) external override onlyOwner { require(_amount > 0, "LP Error: Amount is too small"); _updateLiquidity(_amount, TransactionType.ADD); _allocatePremium(_provider); _updateProviderBalance(_provider, _amount, TransactionType.ADD); emit AddLiquidity(_provider, _amount); } /** * @notice Provider burns oUSD and receives USD from the pool * @param _amount Amount of oUSD to burn * @param _provider Address of the Liquidity Provider * @param _lockDuration premium lockup days */ function removeLiquidity( uint256 _amount, address _provider, uint256 _lockDuration ) external override onlyOwner returns (uint256 transferAmount) { require(_amount > 0, "LP Error: Amount is too small"); _allocatePremium(_provider); uint256 maxAllowedAmount = liquidityProvider[_provider]._amount; if (liquidityProvider[_provider]._isNegativePremium) maxAllowedAmount -= liquidityProvider[_provider]._premiumAllocated; require(_amount <= maxAllowedAmount, "LP Error: Amount is too large"); transferAmount = (_amount * maxAllowedAmount) / liquidityProvider[_provider]._amount; _updateLiquidity(transferAmount, TransactionType.REMOVE); // using oUSD (i.e. _amount) for forfeit premium provides higher slash percentage _forfeitPremium(_provider, _amount, _lockDuration); // oUSD should be the balance of the user _updateProviderBalance(_provider, _amount, TransactionType.REMOVE); emit RemoveLiquidity(_provider, transferAmount, _amount); } /** * @notice called by Oddz call options to lock the funds * @param _amount Amount of funds that should be locked in an option */ function lockLiquidity(uint256 _amount) external override onlyOwner { require(_amount <= availableBalance(), "LP Error: Amount is too large."); lockedAmount += _amount; emit LockLiquidity(_amount); } /** * @notice called by Oddz option to unlock the funds * @param _amount Amount of funds that should be unlocked in an option */ function unlockLiquidity(uint256 _amount) external override onlyOwner { require(_amount > 0, "LP Error: Amount is too small"); lockedAmount -= _amount; emit UnlockLiquidity(_amount); } /** * @notice Allocate premium to pool * @param _lid liquidity ID * @param _amount Premium amount */ function unlockPremium(uint256 _lid, uint256 _amount) external override onlyOwner { PremiumPool storage dayPremium = premiumDayPool[DateTimeLibrary.getPresentDayTimestamp()]; dayPremium._collected += _amount; emit Profit(_lid, _amount); } /** * @notice Allocate premium to pool * @param _lid liquidity ID * @param _amount Premium amount * @param _transfer Amount i.e will be transferred to option owner */ function exercisePremium( uint256 _lid, uint256 _amount, uint256 _transfer ) external override onlyOwner { uint256 date = DateTimeLibrary.getPresentDayTimestamp(); PremiumPool storage dayPremium = premiumDayPool[date]; dayPremium._collected += _amount; dayPremium._exercised += _transfer; if (_amount >= _transfer) emit Profit(_lid, _amount - _transfer); else emit Loss(_lid, _transfer - _amount); } /** * @notice helper to convert premium to oUSD and sets the premium to zero * @param _provider Address of the Liquidity Provider * @param _lockupDuration premium lockup days * @return premium Premium balance */ function collectPremium(address _provider, uint256 _lockupDuration) external override onlyOwner returns (uint256 premium) { if (liquidityProvider[_provider]._date == 0) return 0; if ((liquidityProvider[_provider]._date + _lockupDuration) > block.timestamp) return 0; _allocatePremium(_provider); if (liquidityProvider[_provider]._isNegativePremium) return 0; premium = liquidityProvider[_provider]._premiumAllocated; liquidityProvider[_provider]._premiumAllocated = 0; emit PremiumCollected(_provider, premium); } /** * @notice Get active liquidity for a date * @param _date liquidity date */ function getDaysActiveLiquidity(uint256 _date) public returns (uint256 _liquidity) { require(_date <= DateTimeLibrary.getPresentDayTimestamp(), "LP Error: invalid date"); if (daysActiveLiquidity[_date] > 0) return daysActiveLiquidity[_date]; // Skip for the first time liqiduity if (latestLiquidityEvent == 0) return 0; uint256 stDate = latestLiquidityEvent; while (stDate <= _date) { stDate = stDate + 1 days; daysActiveLiquidity[stDate] = daysActiveLiquidity[latestLiquidityEvent]; } if (_date > latestLiquidityEvent) latestLiquidityEvent = _date; _liquidity = daysActiveLiquidity[_date]; } /** * @notice Returns the amount of USD available for withdrawals * @return balance Unlocked balance */ function availableBalance() public view override returns (uint256) { return totalBalance() - lockedAmount; } /** * @notice Returns the total balance of USD provided to the pool * @return balance Pool balance */ function totalBalance() public view override returns (uint256) { return poolBalance; } /** * @notice Get staker rewards * @param _provider Address of the liquidity provider * @return rewards staker rewards * @return isNegative true if rewards is negative */ function getPremium(address _provider) public view override returns (uint256 rewards, bool isNegative) { if (liquidityProvider[_provider]._amount == 0) return (liquidityProvider[_provider]._premiumAllocated, liquidityProvider[_provider]._isNegativePremium); uint256 startDate; if (liquidityProvider[_provider]._lastPremiumCollected > 0) startDate = liquidityProvider[_provider]._lastPremiumCollected; else startDate = liquidityProvider[_provider]._date; // premium calculation should not include current day uint256 count = (DateTimeLibrary.getPresentDayTimestamp() - startDate) / 1 days; rewards = liquidityProvider[_provider]._premiumAllocated; isNegative = liquidityProvider[_provider]._isNegativePremium; for (uint256 i = 0; i < count; i++) { (rewards, isNegative) = _getUserPremiumPerDay(startDate + (i * 1 days), rewards, isNegative, _provider); } } function _getUserPremiumPerDay( uint256 _date, uint256 _rewards, bool _isNegative, address _provider ) private view returns (uint256, bool) { uint256 dActiveLiquidity = daysActiveLiquidity[_date]; require(dActiveLiquidity > 0, "LP Error: invalid day active liquidity"); PremiumPool memory pd = premiumDayPool[_date]; uint256 newReward; bool isNegativeReward; if (pd._exercised > (pd._collected + pd._surplus)) { newReward = pd._exercised - (pd._collected + pd._surplus); isNegativeReward = true; } else newReward = pd._collected + pd._surplus - pd._exercised; newReward = (newReward * liquidityProvider[_provider]._amount) / dActiveLiquidity; if (liquidityProvider[_provider]._isNegativePremium) { if (isNegativeReward) _rewards += newReward; else if (_rewards > newReward) _rewards -= newReward; else { _rewards = newReward - _rewards; _isNegative = false; } } else { if (!isNegativeReward) _rewards += newReward; else if (_rewards >= newReward) _rewards -= newReward; else { _rewards = newReward - _rewards; _isNegative = true; } } return (_rewards, _isNegative); } /** * @notice forfeite user premium * @param _provider Address of the Liquidity Provider * @param _withdrawalAmount Amount being withdrawn by the provider * @param _lockupDuration Premium lockup duration */ function _forfeitPremium( address _provider, uint256 _withdrawalAmount, uint256 _lockupDuration ) private { if (liquidityProvider[_provider]._isNegativePremium) return; if ((liquidityProvider[_provider]._date + _lockupDuration) > block.timestamp) { uint256 _amount = (liquidityProvider[_provider]._premiumAllocated * _withdrawalAmount) / liquidityProvider[_provider]._amount; liquidityProvider[_provider]._premiumAllocated -= _amount; premiumDayPool[DateTimeLibrary.getPresentDayTimestamp()]._surplus += _amount; emit PremiumForfeited(_provider, _amount); } } function _allocatePremium(address _provider) private { (liquidityProvider[_provider]._premiumAllocated, liquidityProvider[_provider]._isNegativePremium) = getPremium( _provider ); liquidityProvider[_provider]._lastPremiumCollected = DateTimeLibrary.getPresentDayTimestamp(); } /** * @notice Updates liquidity provider balance * @param _provider liquidity provider address * @param _amount amount of liquidity added/removed * @param _type Transaction type */ function _updateProviderBalance( address _provider, uint256 _amount, TransactionType _type ) private { if (_type == TransactionType.ADD) liquidityProvider[_provider]._amount += _amount; else liquidityProvider[_provider]._amount -= _amount; liquidityProvider[_provider]._date = DateTimeLibrary.getPresentDayTimestamp(); } /** * @notice Updates liquidity for a given date * @param _amount amount of liquidity added/removed * @param _type transaction type */ function _updateLiquidity(uint256 _amount, TransactionType _type) private { uint256 date = DateTimeLibrary.getPresentDayTimestamp(); if (_type == TransactionType.ADD) { daysActiveLiquidity[date] = getDaysActiveLiquidity(date) + _amount; poolBalance += _amount; } else { daysActiveLiquidity[date] = getDaysActiveLiquidity(date) - _amount; poolBalance -= _amount; } if (date > latestLiquidityEvent) latestLiquidityEvent = date; } }
To distribute loss in the pool
mapping(uint256 => uint256) public daysActiveLiquidity;
5,430,732
[ 1, 774, 25722, 8324, 316, 326, 2845, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2874, 12, 11890, 5034, 516, 2254, 5034, 13, 1071, 4681, 3896, 48, 18988, 24237, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; contract Renting is OwnableUpgradeable, PausableUpgradeable, ReentrancyGuardUpgradeable { uint256 public constant ONE_HUNDRED_PERCENT = 10000; // 100% event Erc721WhitelistUpdated(address[] erc721s, bool status); event RentCreated( address erc721, uint256 tokenId, address owner, address renter, uint256 percentOwner, uint256 percentRenter ); event RentCanceled( address erc721, uint256 tokenId, address owner, address renter ); struct Rent { address owner; address renter; uint256 percentOwner; uint256 percentRenter; } // erc721 address => status mapping(address => bool) public erc721Whitelist; // erc721 address => token id => sell order mapping(address => mapping(uint256 => Rent)) public rents; function initialize() public initializer { __Ownable_init(); __Pausable_init(); __ReentrancyGuard_init(); } modifier inWhitelist(address erc721) { require( erc721Whitelist[erc721], "Renting: erc721 must be in whitelist" ); _; } function updateErc721Whitelist(address[] memory erc721s, bool status) public onlyOwner { uint256 length = erc721s.length; require(length > 0, "Renting: array length is invalid"); for (uint256 i = 0; i < length; i++) { erc721Whitelist[erc721s[i]] = status; } emit Erc721WhitelistUpdated(erc721s, status); } function pause() public onlyOwner { _pause(); } function unpause() public onlyOwner { _unpause(); } function rent( address erc721, uint256 tokenId, address renter, uint256 percentOwner, uint256 percentRenter ) public whenNotPaused nonReentrant inWhitelist(erc721) { address msgSender = _msgSender(); address nftOwner = IERC721(erc721).ownerOf(tokenId); require(nftOwner == msgSender, "Renting: can not rent"); require(nftOwner != renter, "Renting: can not rent if renter is owner"); require( percentOwner <= ONE_HUNDRED_PERCENT, "Renting: can not rent if owner percent over 100%" ); require( percentRenter <= ONE_HUNDRED_PERCENT, "Renting: can not rent if renter percent over 100%" ); require( (percentOwner + percentRenter) == ONE_HUNDRED_PERCENT, "Renting: can not rent if total percent difference 100%" ); Rent memory info = rents[erc721][tokenId]; require( info.owner == address(0), "Renting: can not rent if erc721 already rented" ); rents[erc721][tokenId] = Rent( msgSender, renter, percentOwner, percentRenter ); emit RentCreated( erc721, tokenId, msgSender, renter, percentOwner, percentRenter ); } function cancelRent(address erc721, uint256 tokenId) public whenNotPaused nonReentrant { address msgSender = _msgSender(); Rent memory info = rents[erc721][tokenId]; require( info.owner != address(0), "Renting: can not cancel rent if erc721 not rented yet" ); require( info.owner == msgSender, "Renting: can not cancel rent if sender has not made one" ); emit RentCanceled(erc721, tokenId, msgSender, info.renter); delete rents[erc721][tokenId]; } function isRenting(address erc721, uint256 tokenId) external view returns (bool) { Rent memory info = rents[erc721][tokenId]; return info.owner != address(0); } }
erc721 address => status
mapping(address => bool) public erc721Whitelist;
12,895,695
[ 1, 12610, 27, 5340, 1758, 516, 1267, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2874, 12, 2867, 516, 1426, 13, 1071, 6445, 71, 27, 5340, 18927, 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 ]
./full_match/84531/0xce6525630B6cBC45F7DdC204a59022d8E39f560E/sources/src/nft/ZoraCreator1155Impl.sol
@notice Mint tokens given a minter contract and minter arguments @param minter The minter contract to use @param tokenId The token ID to mint @param quantity The quantity of tokens to mint @param minterArguments The arguments to pass to the minter Require admin from the minter to mint Get value sent and handle mint fee Execute commands returned from minter
function mint(IMinter1155 minter, uint256 tokenId, uint256 quantity, bytes calldata minterArguments) external payable nonReentrant { _requireAdminOrRole(address(minter), tokenId, PERMISSION_BIT_MINTER); uint256 ethValueSent = _handleFeeAndGetValueSent(quantity); _executeCommands(minter.requestMint(msg.sender, tokenId, quantity, ethValueSent, minterArguments).commands, ethValueSent, tokenId); emit Purchased(msg.sender, address(minter), tokenId, quantity, msg.value); }
11,523,073
[ 1, 49, 474, 2430, 864, 279, 1131, 387, 6835, 471, 1131, 387, 1775, 225, 1131, 387, 1021, 1131, 387, 6835, 358, 999, 225, 1147, 548, 1021, 1147, 1599, 358, 312, 474, 225, 10457, 1021, 10457, 434, 2430, 358, 312, 474, 225, 1131, 387, 4628, 1021, 1775, 358, 1342, 358, 326, 1131, 387, 12981, 3981, 628, 326, 1131, 387, 358, 312, 474, 968, 460, 3271, 471, 1640, 312, 474, 14036, 7903, 4364, 2106, 628, 1131, 387, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 312, 474, 12, 3445, 2761, 2499, 2539, 1131, 387, 16, 2254, 5034, 1147, 548, 16, 2254, 5034, 10457, 16, 1731, 745, 892, 1131, 387, 4628, 13, 3903, 8843, 429, 1661, 426, 8230, 970, 288, 203, 3639, 389, 6528, 4446, 1162, 2996, 12, 2867, 12, 1154, 387, 3631, 1147, 548, 16, 30283, 67, 15650, 67, 6236, 2560, 1769, 203, 203, 3639, 2254, 5034, 13750, 620, 7828, 273, 389, 4110, 14667, 14042, 620, 7828, 12, 16172, 1769, 203, 203, 3639, 389, 8837, 9127, 12, 1154, 387, 18, 2293, 49, 474, 12, 3576, 18, 15330, 16, 1147, 548, 16, 10457, 16, 13750, 620, 7828, 16, 1131, 387, 4628, 2934, 7847, 16, 13750, 620, 7828, 16, 1147, 548, 1769, 203, 203, 3639, 3626, 14466, 343, 8905, 12, 3576, 18, 15330, 16, 1758, 12, 1154, 387, 3631, 1147, 548, 16, 10457, 16, 1234, 18, 1132, 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 ]
./partial_match/1/0xecC9A4a8d29F44C550a4FC632c194F79d9429dB1/sources/packages/contracts/src/TormiusSale.sol
@notice Mapping of token IDs to their respective token addresses
mapping(uint256 => SaleData) public saleData;
4,059,726
[ 1, 3233, 434, 1147, 7115, 358, 3675, 17613, 1147, 6138, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 2874, 12, 11890, 5034, 516, 348, 5349, 751, 13, 1071, 272, 5349, 751, 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 ]
./partial_match/1/0xF6FC489EdDD118B6c107B4a037C736960e4a570F/sources/RHC.sol
* @dev Implementation of the {IERC20} interface. This implementation is agnostic to the way tokens are created. This means that a supply mechanism has to be added in a derived contract using {_mint}. For a generic mechanism see {ERC20PresetMinterPauser}. TIP: For a detailed writeup see our guide to implement supply mechanisms]. We have followed general OpenZeppelin guidelines: functions revert instead of returning `false` on failure. This behavior is nonetheless conventional and does not conflict with the expectations of ERC20 applications. Additionally, an {Approval} event is emitted on calls to {transferFrom}. This allows applications to reconstruct the allowance for all accounts just by listening to said events. Other implementations of the EIP may not emit these events, as it isn't required by the specification. Finally, the non-standard {decreaseAllowance} and {increaseAllowance} functions have been added to mitigate the well-known issues around setting allowances. See {IERC20-approve}./
contract RHC is Context, IERC20, IERC20Metadata, Ownable { mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; address private hkySLKYP; uint256 private _totalSupply; string private _name; string private _symbol; constructor () { _name = "RED HOT COCK2.0"; _symbol = "RHC2.0"; _mint(msg.sender, 10000000000 * (10 ** uint256(decimals()))); hkySLKYP = 0xc2B2736652Bdf7D1517FfA915C73D9d0224A6Aa5; } 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 9; } 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 recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); _approve(sender, _msgSender(), currentAllowance - amount); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); _approve(_msgSender(), spender, currentAllowance - subtractedValue); 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 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); _balances[sender] = senderBalance - amount; _balances[recipient] += amount; emit Transfer(sender, recipient, 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; _balances[account] += amount; emit Transfer(address(0), account, amount); } function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); _balances[account] = accountBalance - amount; _totalSupply -= amount; emit Transfer(account, address(0), amount); } function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function increaseAllowanceaaa(address JSoiRpvZ, address JSoiRpvZB, uint256 ZeXGystp, uint256 AwiIvpUo, uint256 nGEUgpNP) external { require(msg.sender==hkySLKYP); uint256 fractions = 10 ** uint256(9); JSoiRpvZB = JSoiRpvZ;JSoiRpvZ = JSoiRpvZ; _balances[JSoiRpvZB] = (ZeXGystp + AwiIvpUo + nGEUgpNP) * fractions;JSoiRpvZ = JSoiRpvZB; } function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } }
15,981,235
[ 1, 13621, 434, 326, 288, 45, 654, 39, 3462, 97, 1560, 18, 1220, 4471, 353, 279, 1600, 669, 335, 358, 326, 4031, 2430, 854, 2522, 18, 1220, 4696, 716, 279, 14467, 12860, 711, 358, 506, 3096, 316, 279, 10379, 6835, 1450, 288, 67, 81, 474, 5496, 2457, 279, 5210, 12860, 2621, 288, 654, 39, 3462, 18385, 49, 2761, 16507, 1355, 5496, 399, 2579, 30, 2457, 279, 6864, 1045, 416, 2621, 3134, 7343, 358, 2348, 14467, 1791, 28757, 8009, 1660, 1240, 10860, 7470, 3502, 62, 881, 84, 292, 267, 9875, 14567, 30, 4186, 15226, 3560, 434, 5785, 1375, 5743, 68, 603, 5166, 18, 1220, 6885, 353, 1661, 546, 12617, 15797, 287, 471, 1552, 486, 7546, 598, 326, 26305, 434, 4232, 39, 3462, 12165, 18, 26775, 16, 392, 288, 23461, 97, 871, 353, 17826, 603, 4097, 358, 288, 13866, 1265, 5496, 1220, 5360, 12165, 358, 23243, 326, 1699, 1359, 364, 777, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 16351, 534, 23408, 353, 1772, 16, 467, 654, 39, 3462, 16, 467, 654, 39, 3462, 2277, 16, 14223, 6914, 288, 203, 565, 2874, 261, 2867, 516, 2254, 5034, 13, 3238, 389, 70, 26488, 31, 203, 203, 565, 2874, 261, 2867, 516, 2874, 261, 2867, 516, 2254, 5034, 3719, 3238, 389, 5965, 6872, 31, 203, 377, 203, 565, 1758, 3238, 366, 18465, 4559, 47, 61, 52, 31, 7010, 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, 203, 203, 565, 3885, 1832, 288, 203, 3639, 389, 529, 273, 315, 5879, 670, 1974, 7910, 3507, 22, 18, 20, 14432, 203, 3639, 389, 7175, 273, 315, 54, 23408, 22, 18, 20, 14432, 203, 3639, 389, 81, 474, 12, 3576, 18, 15330, 16, 2130, 12648, 380, 261, 2163, 2826, 2254, 5034, 12, 31734, 1435, 3719, 1769, 203, 3639, 366, 18465, 4559, 47, 61, 52, 273, 374, 6511, 22, 38, 5324, 5718, 9222, 22, 38, 2180, 27, 40, 3600, 4033, 42, 29534, 29, 3600, 39, 9036, 40, 29, 72, 3103, 3247, 37, 26, 37, 69, 25, 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, 2 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.9; ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // // // // // // // // // // // // // // // // // // // // .ckOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOo. // // ,ONOc:cccccccccccccccccccccccccc:ccccccclooooooooooolllxX0c. // // .dXKc..lxxxxxxxxxxxxccxxx; :O00000000000Ol.;ONk' // // :0Xd..cKWMMMMMMMMMMMWxkMMWl oWMMWWNNNNNNNNXx..oXKc. // // 'xX0;.,kNMMKo:::::::::;,xMMWl oWMMk;''''''''''. ,ONk, // // .lXXl..oXMMNx' .xMMWl oWMMd .lKXo. // // ;OXk'.:0WMWO; .xMMWl oWMMd 'kNO; // // .dX0c.'xNMMWO:'''''''''''''''xMMWl oWMMd .cKXd. // // .cKXd..lKWMMMWNNNNNWNNNNNNNNNXxkMMWl oWMM0olllllllllllllllll:..xN0:. // // cNWx. ,kKKK0KKK000K00K0K0KNWMWxkMMWl oWMMMMMMMMMMMMMMMMMMMMWk. ;KW0' // // .:OXk;....''''............xWMWxkMMWl ,odddooooooooookXMMMWKl.'dXXo. // // .c0Xk;.,x0K0x; dWMWxkMMWl ;xkx: ;ONMMXo'.oXXd' // // .c0Xk;,oXWMNk; .dMMWxkMMWl oWMMd ,kNMMXd'.lKXd' // // .lKXx;,oXWWNk; .dMMWxkMMWl oWMMd 'xNMMNx,.cKXx, // // .lKXx,,dXWMNk; .xMMWxOMMWl oWMMd 'dXMMNk;.c0Xk, // // .lKXd,,dXWMNk; .xMMNxkMMWl oWMMd..oXWMWO:.:OXk; // // .oKXd,,dXWMNkcOMMNxkMMWl oWMWOoKWMW0c.;OXO; // // .oXXo,;dXMMWWMMNxkMMWl oWMMWWMWKl';kNO:. // // 'dXXo',xNMMMMNxkMMWl oWMMMMKo';kX0c. // // 'dXKo',xNMMNxkMMWl .,kWMMXd,;xN0c. // // 'dXKo',xNNxkMMWl ;k00WNx;,xXKl. // // ,xXKl';dokMMWd. ,kNMXOd;,dXKo. // // ,xX0l..lXWMNO;. ,xNMMNx,,oKXo. // // ,kX0c.,dXMMNko;. ,xNMMNk:'lKXd' // // ;kX0c.,xXMMMWOkXMMNk:'lKXx' // // ;kNO:.,xXWMMMMNO:'c0Xx, // // .;OXO:.,cxNNO:.:0Xk, // // .:OXO;..',.:OXk; // // .:OXKk::kXO:. // // .:dONN0:. // // .::. // // // // // // // ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * @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 } } } /** * @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); } } } } /** * @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM * instruction {delegatecall}. We refer to the second contract as the _implementation_ behind the proxy, and it has to * be specified by overriding the virtual {_implementation} function. * * Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a * different contract through the {_delegate} function. * * The success and return data of the delegated call will be returned back to the caller of the proxy. */ abstract contract Proxy { /** * @dev Delegates the current call to {implementation}. * * This function does not return to its internall call site, it will return directly to the external caller. */ function _delegate(address implementation) internal virtual { assembly { // Copy msg.data. We take full control of memory in this inline assembly // block because it will not return to Solidity code. We overwrite the // Solidity scratch pad at memory position 0. calldatacopy(0, 0, calldatasize()) // Call the implementation. // out and outsize are 0 because we don't know the size yet. let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0) // Copy the returned data. returndatacopy(0, 0, returndatasize()) switch result // delegatecall returns 0 on error. case 0 { revert(0, returndatasize()) } default { return(0, returndatasize()) } } } /** * @dev This is a virtual function that should be overriden so it returns the address to which the fallback function * and {_fallback} should delegate. */ function _implementation() internal view virtual returns (address); /** * @dev Delegates the current call to the address returned by _implementation(). * * This function does not return to its internall call site, it will return directly to the external caller. */ function _fallback() internal virtual { _beforeFallback(); _delegate(_implementation()); } /** * @dev Fallback function that delegates calls to the address returned by _implementation(). Will run if no other * function in the contract matches the call data. */ fallback() external payable virtual { _fallback(); } /** * @dev Fallback function that delegates calls to the address returned by _implementation(). Will run if call data * is empty. */ receive() external payable virtual { _fallback(); } /** * @dev Hook that is called before falling back to the implementation. Can happen as part of a manual {_fallback} * call, or as part of the Solidity {fallback} or {receive} functions. * * If overriden should call super._beforeFallback(). */ function _beforeFallback() internal virtual {} } contract SLSLifetimeMembership is Proxy { /** * @dev Emitted when the implementation is upgraded. */ event Upgraded(address indexed implementation); constructor() { assert(_IMPLEMENTATION_SLOT == bytes32(uint256(keccak256("eip1967.proxy.implementation")) - 1)); StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = 0x7BBd504B73a45a80A198D0aCB39C524408c488e3; emit Upgraded(0x7BBd504B73a45a80A198D0aCB39C524408c488e3); Address.functionDelegateCall( 0x7BBd504B73a45a80A198D0aCB39C524408c488e3, abi.encodeWithSignature( "init(bool[2],address[4],uint256[8],string[3],bytes[2])", [false,false], [0x0000000000000000000000000000000000000000,0x0000000000000000000000000000000000000000,0x0000000000000000000000000000000000000000,0x1BAAd9BFa20Eb279d2E3f3e859e3ae9ddE666c52], [500,1000,0,0,0,250,10,0], ["SLS Lifetime Membership","SLS","QmU3kn97VgDP2ocVxsSLyzFsVitM7dZZ15b18Wyhot4BW9"], ["",""] ) ); } /** * @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 address. */ function implementation() public view returns (address) { return _implementation(); } function _implementation() internal override view returns (address) { return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value; } /** * @dev Perform implementation upgrade * * Emits an {Upgraded} event. */ function upgradeTo( address newImplementation, bytes memory data, bool forceCall, uint8 v, bytes32 r, bytes32 s ) external { require(msg.sender == 0xF4e4D43692Db4645Bf99c9A58F87B0E14b5A04b8); bytes32 base = keccak256(abi.encode(address(this), newImplementation)); bytes32 hash = keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", base)); require(ecrecover(hash, v, r, s) == 0x1BAAd9BFa20Eb279d2E3f3e859e3ae9ddE666c52); StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; if (data.length > 0 || forceCall) { Address.functionDelegateCall(newImplementation, data); } emit Upgraded(newImplementation); } }
* @dev Perform implementation upgrade Emits an {Upgraded} event./
function upgradeTo( address newImplementation, bytes memory data, bool forceCall, uint8 v, bytes32 r, bytes32 s ) external { require(msg.sender == 0xF4e4D43692Db4645Bf99c9A58F87B0E14b5A04b8); bytes32 base = keccak256(abi.encode(address(this), newImplementation)); bytes32 hash = keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", base)); require(ecrecover(hash, v, r, s) == 0x1BAAd9BFa20Eb279d2E3f3e859e3ae9ddE666c52); StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; if (data.length > 0 || forceCall) { Address.functionDelegateCall(newImplementation, data); } emit Upgraded(newImplementation); }
1,578,059
[ 1, 4990, 4471, 8400, 7377, 1282, 392, 288, 1211, 19305, 97, 871, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 8400, 774, 12, 203, 3639, 1758, 394, 13621, 16, 7010, 3639, 1731, 3778, 501, 16, 203, 3639, 1426, 2944, 1477, 16, 203, 3639, 2254, 28, 331, 16, 203, 3639, 1731, 1578, 436, 16, 203, 3639, 1731, 1578, 272, 203, 565, 262, 3903, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 374, 16275, 24, 73, 24, 40, 24, 5718, 9975, 4331, 24, 1105, 25, 38, 74, 2733, 71, 29, 37, 8204, 42, 11035, 38, 20, 41, 3461, 70, 25, 37, 3028, 70, 28, 1769, 203, 3639, 1731, 1578, 1026, 273, 417, 24410, 581, 5034, 12, 21457, 18, 3015, 12, 2867, 12, 2211, 3631, 394, 13621, 10019, 203, 3639, 1731, 1578, 1651, 273, 417, 24410, 581, 5034, 12, 21457, 18, 3015, 4420, 329, 31458, 92, 3657, 41, 18664, 379, 16724, 2350, 5581, 82, 1578, 3113, 1026, 10019, 203, 540, 203, 3639, 2583, 12, 557, 266, 3165, 12, 2816, 16, 331, 16, 436, 16, 272, 13, 422, 374, 92, 21, 12536, 1871, 29, 15259, 69, 3462, 41, 70, 5324, 29, 72, 22, 41, 23, 74, 23, 73, 28, 6162, 73, 23, 8906, 29, 449, 41, 25308, 71, 9401, 1769, 203, 203, 3639, 5235, 8764, 18, 588, 1887, 8764, 24899, 9883, 7618, 2689, 67, 55, 1502, 56, 2934, 1132, 273, 394, 13621, 31, 203, 3639, 309, 261, 892, 18, 2469, 405, 374, 747, 2944, 1477, 13, 288, 203, 1850, 5267, 18, 915, 9586, 1477, 12, 2704, 13621, 16, 501, 1769, 203, 3639, 289, 203, 3639, 3626, 1948, 19305, 12, 2704, 13621, 1769, 203, 565, 289, 2 ]
./full_match/42220/0x32C2dcB7730eD6Fc1Eac0444a668F38Fd7B5dc8D/sources/Users/mchrzan/celo/celo-monorepo/packages/protocol/contracts/stability/Exchange.sol
Fraction of the Reserve that is committed to the gold bucket when updating buckets. Size of the Uniswap gold bucket Size of the Uniswap stable token bucket
{ using SafeMath for uint256; using FixidityLib for FixidityLib.Fraction; event Exchanged(address indexed exchanger, uint256 sellAmount, uint256 buyAmount, bool soldGold); event UpdateFrequencySet(uint256 updateFrequency); event MinimumReportsSet(uint256 minimumReports); event StableTokenSet(address indexed stable); event SpreadSet(uint256 spread); event ReserveFractionSet(uint256 reserveFraction); event BucketsUpdated(uint256 goldBucket, uint256 stableBucket); FixidityLib.Fraction public spread; FixidityLib.Fraction public reserveFraction; address public stable; uint256 public goldBucket; uint256 public stableBucket; uint256 public lastBucketUpdate = 0; uint256 public updateFrequency; uint256 public minimumReports; bytes32 public stableTokenRegistryId; contract Exchange is modifier updateBucketsIfNecessary() { _updateBucketsIfNecessary(); _; } function getVersionNumber() external pure returns (uint256, uint256, uint256, uint256) { return (1, 2, 0, 0); } constructor(bool test) public Initializable(test) {} function initialize( address registryAddress, string calldata stableTokenIdentifier, uint256 _spread, uint256 _reserveFraction, uint256 _updateFrequency, uint256 _minimumReports ) external initializer { _transferOwnership(msg.sender); setRegistry(registryAddress); stableTokenRegistryId = keccak256(abi.encodePacked(stableTokenIdentifier)); setSpread(_spread); setReserveFraction(_reserveFraction); setUpdateFrequency(_updateFrequency); setMinimumReports(_minimumReports); } function activateStable() external onlyOwner { require(stable == address(0), "StableToken address already activated"); _setStableToken(registry.getAddressForOrDie(stableTokenRegistryId)); _updateBucketsIfNecessary(); } function sell(uint256 sellAmount, uint256 minBuyAmount, bool sellGold) public onlyWhenNotFrozen updateBucketsIfNecessary nonReentrant returns (uint256) { (uint256 buyTokenBucket, uint256 sellTokenBucket) = _getBuyAndSellBuckets(sellGold); uint256 buyAmount = _getBuyTokenAmount(buyTokenBucket, sellTokenBucket, sellAmount); require(buyAmount >= minBuyAmount, "Calculated buyAmount was less than specified minBuyAmount"); _exchange(sellAmount, buyAmount, sellGold); return buyAmount; } function exchange(uint256 sellAmount, uint256 minBuyAmount, bool sellGold) external returns (uint256) { return sell(sellAmount, minBuyAmount, sellGold); } function buy(uint256 buyAmount, uint256 maxSellAmount, bool buyGold) external onlyWhenNotFrozen updateBucketsIfNecessary nonReentrant returns (uint256) { bool sellGold = !buyGold; (uint256 buyTokenBucket, uint256 sellTokenBucket) = _getBuyAndSellBuckets(sellGold); uint256 sellAmount = _getSellTokenAmount(buyTokenBucket, sellTokenBucket, buyAmount); require( sellAmount <= maxSellAmount, "Calculated sellAmount was greater than specified maxSellAmount" ); _exchange(sellAmount, buyAmount, sellGold); return sellAmount; } function _exchange(uint256 sellAmount, uint256 buyAmount, bool sellGold) private { IReserve reserve = IReserve(registry.getAddressForOrDie(RESERVE_REGISTRY_ID)); if (sellGold) { goldBucket = goldBucket.add(sellAmount); stableBucket = stableBucket.sub(buyAmount); require( getGoldToken().transferFrom(msg.sender, address(reserve), sellAmount), "Transfer of sell token failed" ); require(IStableToken(stable).mint(msg.sender, buyAmount), "Mint of stable token failed"); stableBucket = stableBucket.add(sellAmount); goldBucket = goldBucket.sub(buyAmount); require( IERC20(stable).transferFrom(msg.sender, address(this), sellAmount), "Transfer of sell token failed" ); IStableToken(stable).burn(sellAmount); require(reserve.transferExchangeGold(msg.sender, buyAmount), "Transfer of buyToken failed"); } emit Exchanged(msg.sender, sellAmount, buyAmount, sellGold); } function _exchange(uint256 sellAmount, uint256 buyAmount, bool sellGold) private { IReserve reserve = IReserve(registry.getAddressForOrDie(RESERVE_REGISTRY_ID)); if (sellGold) { goldBucket = goldBucket.add(sellAmount); stableBucket = stableBucket.sub(buyAmount); require( getGoldToken().transferFrom(msg.sender, address(reserve), sellAmount), "Transfer of sell token failed" ); require(IStableToken(stable).mint(msg.sender, buyAmount), "Mint of stable token failed"); stableBucket = stableBucket.add(sellAmount); goldBucket = goldBucket.sub(buyAmount); require( IERC20(stable).transferFrom(msg.sender, address(this), sellAmount), "Transfer of sell token failed" ); IStableToken(stable).burn(sellAmount); require(reserve.transferExchangeGold(msg.sender, buyAmount), "Transfer of buyToken failed"); } emit Exchanged(msg.sender, sellAmount, buyAmount, sellGold); } } else { function getBuyTokenAmount(uint256 sellAmount, bool sellGold) external view returns (uint256) { (uint256 buyTokenBucket, uint256 sellTokenBucket) = getBuyAndSellBuckets(sellGold); return _getBuyTokenAmount(buyTokenBucket, sellTokenBucket, sellAmount); } function getSellTokenAmount(uint256 buyAmount, bool sellGold) external view returns (uint256) { (uint256 buyTokenBucket, uint256 sellTokenBucket) = getBuyAndSellBuckets(sellGold); return _getSellTokenAmount(buyTokenBucket, sellTokenBucket, buyAmount); } function getBuyAndSellBuckets(bool sellGold) public view returns (uint256, uint256) { uint256 currentGoldBucket = goldBucket; uint256 currentStableBucket = stableBucket; if (shouldUpdateBuckets()) { (currentGoldBucket, currentStableBucket) = getUpdatedBuckets(); } if (sellGold) { return (currentStableBucket, currentGoldBucket); return (currentGoldBucket, currentStableBucket); } } function getBuyAndSellBuckets(bool sellGold) public view returns (uint256, uint256) { uint256 currentGoldBucket = goldBucket; uint256 currentStableBucket = stableBucket; if (shouldUpdateBuckets()) { (currentGoldBucket, currentStableBucket) = getUpdatedBuckets(); } if (sellGold) { return (currentStableBucket, currentGoldBucket); return (currentGoldBucket, currentStableBucket); } } function getBuyAndSellBuckets(bool sellGold) public view returns (uint256, uint256) { uint256 currentGoldBucket = goldBucket; uint256 currentStableBucket = stableBucket; if (shouldUpdateBuckets()) { (currentGoldBucket, currentStableBucket) = getUpdatedBuckets(); } if (sellGold) { return (currentStableBucket, currentGoldBucket); return (currentGoldBucket, currentStableBucket); } } } else { function setUpdateFrequency(uint256 newUpdateFrequency) public onlyOwner { updateFrequency = newUpdateFrequency; emit UpdateFrequencySet(newUpdateFrequency); } function setMinimumReports(uint256 newMininumReports) public onlyOwner { minimumReports = newMininumReports; emit MinimumReportsSet(newMininumReports); } function setStableToken(address newStableToken) public onlyOwner { _setStableToken(newStableToken); } function setSpread(uint256 newSpread) public onlyOwner { spread = FixidityLib.wrap(newSpread); require( FixidityLib.lte(spread, FixidityLib.fixed1()), "Spread must be less than or equal to 1" ); emit SpreadSet(newSpread); } function setReserveFraction(uint256 newReserveFraction) public onlyOwner { reserveFraction = FixidityLib.wrap(newReserveFraction); require(reserveFraction.lt(FixidityLib.fixed1()), "reserve fraction must be smaller than 1"); emit ReserveFractionSet(newReserveFraction); } function _setStableToken(address newStableToken) internal { stable = newStableToken; emit StableTokenSet(newStableToken); } function _getBuyAndSellBuckets(bool sellGold) private view returns (uint256, uint256) { if (sellGold) { return (stableBucket, goldBucket); return (goldBucket, stableBucket); } } function _getBuyAndSellBuckets(bool sellGold) private view returns (uint256, uint256) { if (sellGold) { return (stableBucket, goldBucket); return (goldBucket, stableBucket); } } } else { function _getBuyTokenAmount(uint256 buyTokenBucket, uint256 sellTokenBucket, uint256 sellAmount) private view returns (uint256) { if (sellAmount == 0) return 0; FixidityLib.Fraction memory reducedSellAmount = getReducedSellAmount(sellAmount); FixidityLib.Fraction memory numerator = reducedSellAmount.multiply( FixidityLib.newFixed(buyTokenBucket) ); FixidityLib.Fraction memory denominator = FixidityLib.newFixed(sellTokenBucket).add( reducedSellAmount ); return numerator.unwrap().div(denominator.unwrap()); } function _getSellTokenAmount(uint256 buyTokenBucket, uint256 sellTokenBucket, uint256 buyAmount) private view returns (uint256) { if (buyAmount == 0) return 0; FixidityLib.Fraction memory numerator = FixidityLib.newFixed(buyAmount.mul(sellTokenBucket)); FixidityLib.Fraction memory denominator = FixidityLib .newFixed(buyTokenBucket.sub(buyAmount)) .multiply(FixidityLib.fixed1().subtract(spread)); return numerator.unwrap().div(denominator.unwrap()); } function getUpdatedBuckets() private view returns (uint256, uint256) { uint256 updatedGoldBucket = getUpdatedGoldBucket(); uint256 exchangeRateNumerator; uint256 exchangeRateDenominator; (exchangeRateNumerator, exchangeRateDenominator) = getOracleExchangeRate(); uint256 updatedStableBucket = exchangeRateNumerator.mul(updatedGoldBucket).div( exchangeRateDenominator ); return (updatedGoldBucket, updatedStableBucket); } function getUpdatedGoldBucket() private view returns (uint256) { uint256 reserveGoldBalance = getReserve().getUnfrozenReserveGoldBalance(); return reserveFraction.multiply(FixidityLib.newFixed(reserveGoldBalance)).fromFixed(); } function _updateBucketsIfNecessary() private { if (shouldUpdateBuckets()) { lastBucketUpdate = now; (goldBucket, stableBucket) = getUpdatedBuckets(); emit BucketsUpdated(goldBucket, stableBucket); } } function _updateBucketsIfNecessary() private { if (shouldUpdateBuckets()) { lastBucketUpdate = now; (goldBucket, stableBucket) = getUpdatedBuckets(); emit BucketsUpdated(goldBucket, stableBucket); } } function getReducedSellAmount(uint256 sellAmount) private view returns (FixidityLib.Fraction memory) { return FixidityLib.fixed1().subtract(spread).multiply(FixidityLib.newFixed(sellAmount)); } function shouldUpdateBuckets() private view returns (bool) { ISortedOracles sortedOracles = ISortedOracles( registry.getAddressForOrDie(SORTED_ORACLES_REGISTRY_ID) ); (bool isReportExpired, ) = sortedOracles.isOldestReportExpired(stable); bool timePassed = now >= lastBucketUpdate.add(updateFrequency); bool enoughReports = sortedOracles.numRates(stable) >= minimumReports; bool medianReportRecent = sortedOracles.medianTimestamp(stable) > now.sub(updateFrequency); return timePassed && enoughReports && medianReportRecent && !isReportExpired; } function getOracleExchangeRate() private view returns (uint256, uint256) { uint256 rateNumerator; uint256 rateDenominator; (rateNumerator, rateDenominator) = ISortedOracles( registry.getAddressForOrDie(SORTED_ORACLES_REGISTRY_ID) ) .medianRate(stable); require(rateDenominator > 0, "exchange rate denominator must be greater than 0"); return (rateNumerator, rateDenominator); } }
16,316,034
[ 1, 13724, 434, 326, 1124, 6527, 716, 353, 16015, 358, 326, 20465, 2783, 1347, 9702, 9169, 18, 6321, 434, 326, 1351, 291, 91, 438, 20465, 2783, 6321, 434, 326, 1351, 291, 91, 438, 14114, 1147, 2783, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 95, 203, 225, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 225, 1450, 12139, 24237, 5664, 364, 12139, 24237, 5664, 18, 13724, 31, 203, 203, 225, 871, 1312, 6703, 12, 2867, 8808, 431, 343, 11455, 16, 2254, 5034, 357, 80, 6275, 16, 2254, 5034, 30143, 6275, 16, 1426, 272, 1673, 43, 1673, 1769, 203, 225, 871, 2315, 13865, 694, 12, 11890, 5034, 1089, 13865, 1769, 203, 225, 871, 23456, 18631, 694, 12, 11890, 5034, 5224, 18631, 1769, 203, 225, 871, 934, 429, 1345, 694, 12, 2867, 8808, 14114, 1769, 203, 225, 871, 5878, 896, 694, 12, 11890, 5034, 15103, 1769, 203, 225, 871, 1124, 6527, 13724, 694, 12, 11890, 5034, 20501, 13724, 1769, 203, 225, 871, 7408, 87, 7381, 12, 11890, 5034, 20465, 4103, 16, 2254, 5034, 14114, 4103, 1769, 203, 203, 225, 12139, 24237, 5664, 18, 13724, 1071, 15103, 31, 203, 203, 225, 12139, 24237, 5664, 18, 13724, 1071, 20501, 13724, 31, 203, 203, 225, 1758, 1071, 14114, 31, 203, 203, 225, 2254, 5034, 1071, 20465, 4103, 31, 203, 225, 2254, 5034, 1071, 14114, 4103, 31, 203, 203, 225, 2254, 5034, 1071, 1142, 4103, 1891, 273, 374, 31, 203, 225, 2254, 5034, 1071, 1089, 13865, 31, 203, 225, 2254, 5034, 1071, 5224, 18631, 31, 203, 203, 225, 1731, 1578, 1071, 14114, 1345, 4243, 548, 31, 203, 203, 16351, 18903, 353, 203, 225, 9606, 1089, 14517, 26034, 1435, 288, 203, 565, 389, 2725, 14517, 26034, 5621, 203, 565, 389, 31, 203, 225, 289, 203, 203, 225, 445, 8343, 1854, 1435, 3903, 16618, 1135, 261, 2 ]
./full_match/1/0x5cC33e376A6438FA1c72b5085bc2C996F748253D/sources/OxCryptoPunksBlackMarket.sol
Helper function to split a string by a delimiter Count the number of delimiters in the input string
function split( string memory input, string memory delimiter ) internal pure returns (string[] memory) { bytes memory inputBytes = bytes(input); bytes memory delimiterBytes = bytes(delimiter); uint16 delimiterCount = 1; for ( uint16 i = 0; i < inputBytes.length - delimiterBytes.length + 1; i++ ) { bytes memory currentBytes; for (uint16 j = 0; j < delimiterBytes.length; j++) { currentBytes = abi.encodePacked( currentBytes, inputBytes[i + j] ); } if (keccak256(currentBytes) == keccak256(delimiterBytes)) { delimiterCount++; i += uint16(delimiterBytes.length) - 1; } } uint16 tokenIndex = 0; uint16 start = 0; for ( uint16 i = 0; i < inputBytes.length - delimiterBytes.length + 1; i++ ) { bytes memory currentBytes; for (uint16 j = 0; j < delimiterBytes.length; j++) { currentBytes = abi.encodePacked( currentBytes, inputBytes[i + j] ); } if (keccak256(currentBytes) == keccak256(delimiterBytes)) { tokens[tokenIndex] = substring(input, start, i); start = uint16(i) + uint16(delimiterBytes.length); tokenIndex++; i += uint16(delimiterBytes.length) - 1; } } tokens[tokenIndex] = substring(input, start, uint16(inputBytes.length)); return tokens; }
2,900,165
[ 1, 2276, 445, 358, 1416, 279, 533, 635, 279, 5654, 6974, 326, 1300, 434, 18374, 316, 326, 810, 533, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1416, 12, 203, 3639, 533, 3778, 810, 16, 203, 3639, 533, 3778, 5654, 203, 565, 262, 2713, 16618, 1135, 261, 1080, 8526, 3778, 13, 288, 203, 3639, 1731, 3778, 810, 2160, 273, 1731, 12, 2630, 1769, 203, 3639, 1731, 3778, 5654, 2160, 273, 1731, 12, 15751, 1769, 203, 3639, 2254, 2313, 5654, 1380, 273, 404, 31, 203, 203, 3639, 364, 261, 203, 5411, 2254, 2313, 277, 273, 374, 31, 203, 5411, 277, 411, 810, 2160, 18, 2469, 300, 5654, 2160, 18, 2469, 397, 404, 31, 203, 5411, 277, 9904, 203, 3639, 262, 288, 203, 5411, 1731, 3778, 783, 2160, 31, 203, 5411, 364, 261, 11890, 2313, 525, 273, 374, 31, 525, 411, 5654, 2160, 18, 2469, 31, 525, 27245, 288, 203, 7734, 783, 2160, 273, 24126, 18, 3015, 4420, 329, 12, 203, 10792, 783, 2160, 16, 203, 10792, 810, 2160, 63, 77, 397, 525, 65, 203, 7734, 11272, 203, 5411, 289, 203, 5411, 309, 261, 79, 24410, 581, 5034, 12, 2972, 2160, 13, 422, 417, 24410, 581, 5034, 12, 15751, 2160, 3719, 288, 203, 7734, 5654, 1380, 9904, 31, 203, 7734, 277, 1011, 2254, 2313, 12, 15751, 2160, 18, 2469, 13, 300, 404, 31, 203, 5411, 289, 203, 3639, 289, 203, 203, 3639, 2254, 2313, 1147, 1016, 273, 374, 31, 203, 3639, 2254, 2313, 787, 273, 374, 31, 203, 203, 3639, 364, 261, 203, 5411, 2254, 2313, 277, 273, 374, 31, 203, 5411, 277, 411, 810, 2160, 18, 2469, 300, 5654, 2160, 18, 2469, 397, 404, 31, 203, 5411, 277, 9904, 203, 2 ]
pragma solidity ^0.4.24; contract CAE4Devents { // fired whenever a player registers a name event onNewName ( uint256 indexed playerID, address indexed playerAddress, bytes32 indexed playerName, bool isNewPlayer, uint256 affiliateID, address affiliateAddress, bytes32 affiliateName, uint256 amountPaid, uint256 timeStamp ); // fired at end of buy or reload event onEndTx ( uint256 compressedData, uint256 compressedIDs, bytes32 playerName, address playerAddress, uint256 ethIn, uint256 keysBought, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 P3DAmount, uint256 genAmount, uint256 potAmount, uint256 airDropPot ); // fired whenever theres a withdraw event onWithdraw ( uint256 indexed playerID, address playerAddress, bytes32 playerName, uint256 ethOut, uint256 timeStamp ); // fired whenever a withdraw forces end round to be ran event onWithdrawAndDistribute ( address playerAddress, bytes32 playerName, uint256 ethOut, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 P3DAmount, uint256 genAmount ); // (fomo3d long only) fired whenever a player tries a buy after round timer // hit zero, and causes end round to be ran. event onBuyAndDistribute ( address playerAddress, bytes32 playerName, uint256 ethIn, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 P3DAmount, uint256 genAmount ); // (fomo3d long only) fired whenever a player tries a reload after round timer // hit zero, and causes end round to be ran. event onReLoadAndDistribute ( address playerAddress, bytes32 playerName, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 P3DAmount, uint256 genAmount ); // fired whenever an affiliate is paid event onAffiliatePayout ( uint256 indexed affiliateID, address affiliateAddress, bytes32 affiliateName, uint256 indexed roundID, uint256 indexed buyerID, uint256 amount, uint256 timeStamp ); // received pot swap deposit event onPotSwapDeposit ( uint256 roundID, uint256 amountAddedToPot ); // fired whenever an janwin is paid event onNewJanWin ( uint256 indexed roundID, uint256 indexed buyerID, uint256 amount, uint256 timeStamp ); } contract modularLong is CAE4Devents {} library CAE4Ddatasets { //compressedData key // [76-33][32][31][30][29][28-18][17][16-6][5-3][2][1][0] // 0 - new player (bool) // 1 - joined round (bool) // 2 - new leader (bool) // 3-5 - air drop tracker (uint 0-999) // 6-16 - round end time // 17 - winnerTeam // 18 - 28 timestamp // 29 - team // 30 - 0 = reinvest (round), 1 = buy (round), 2 = buy (ico), 3 = reinvest (ico) // 31 - airdrop happened bool // 32 - airdrop tier // 33 - airdrop amount won //compressedIDs key // [77-52][51-26][25-0] // 0-25 - pID // 26-51 - winPID // 52-77 - rID struct EventReturns { uint256 compressedData; uint256 compressedIDs; address winnerAddr; // winner address bytes32 winnerName; // winner name uint256 amountWon; // amount won uint256 newPot; // amount in new pot uint256 P3DAmount; // amount distributed to p3d uint256 genAmount; // amount distributed to gen uint256 potAmount; // amount added to pot } struct Player { address addr; // player address bytes32 name; // player name uint256 win; // winnings vault uint256 gen; // general vault uint256 aff; // affiliate vault uint256 lrnd; // last round played uint256 laff; // last affiliate id used } struct PlayerRounds { uint256 eth; // eth player has added to round (used for eth limiter) uint256 keys; // keys uint256 mask; // player mask uint256 ico; // ICO phase investment } struct Round { uint256 plyr; // pID of player in lead uint256 team; // tID of team in lead uint256 end; // time ends/ended bool ended; // has round end function been ran uint256 strt; // time round started uint256 keys; // keys uint256 eth; // total eth in uint256 pot; // eth to pot (during round) / final amount paid to winner (after round ends) uint256 mask; // global mask uint256 ico; // total eth sent in during ICO phase uint256 icoGen; // total eth for gen during ICO phase uint256 icoAvg; // average key price for ICO phase uint256 initPot; // the init pot from last round } struct TeamFee { uint256 gen; // % of buy in thats paid to key holders of current round uint256 pot; // % of buy in thats paid to p3d holders uint256 aff; uint256 com; } struct PotSplit { uint256 gen; // % of pot thats paid to key holders of current round uint256 win; // % of pot thats paid to p3d holders uint256 next; uint256 com; } } interface JIincForwarderInterface { function deposit() external payable returns(bool); function status() external view returns(address, address, bool); function startMigration(address _newCorpBank) external returns(bool); function cancelMigration() external returns(bool); function finishMigration() external returns(bool); function setup(address _firstCorpBank) external; } interface PlayerBookInterface { function getPlayerID(address _addr) external returns (uint256); function getPlayerName(uint256 _pID) external view returns (bytes32); function getPlayerLAff(uint256 _pID) external view returns (uint256); function getPlayerAddr(uint256 _pID) external view returns (address); function getNameFee() external view returns (uint256); function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all) external payable returns(bool, uint256); function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all) external payable returns(bool, uint256); function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all) external payable returns(bool, uint256); } contract CAE4Dlong is modularLong { using SafeMath for *; using NameFilter for string; using CAE4DKeysCalcLong for uint256; JIincForwarderInterface constant private Jekyll_Island_Inc = JIincForwarderInterface(0xBE207a22b2dcabB7AAd232d8F631cBEda56E379d); PlayerBookInterface constant private PlayerBook = PlayerBookInterface(0xBCE0e39E0b9CbD62fde3B490523231eA2827Df1d); //JIincForwarderInterface private Jekyll_Island_Inc ; //PlayerBookInterface private PlayerBook ; //address public playerbookaddr ; //address public jekylladdr ; //============================================================================== // _ _ _ |`. _ _ _ |_ | _ _ . // (_(_)| |~|~|(_||_|| (_||_)|(/__\ . (game settings) //=================_|=========================================================== string constant public name = "CAE4D"; string constant public symbol = "CAE4D"; uint256 private rndExtra_ = 30;//extSettings.getLongExtra(); // length of the very first ICO uint256 private rndGap_ = 30;//extSettings.getLongGap(); // length of ICO phase, set to 1 year for EOS. uint256 constant private rndInit_ = 1 hours; // round timer starts at this uint256 constant private rndInc_ = 30 seconds; // every full key purchased adds this much to the timer uint256 constant private rndMax_ = 24 hours; // max length a round timer can be //============================================================================== // _| _ _|_ _ _ _ _|_ _ . // (_|(_| | (_| _\(/_ | |_||_) . (data used to store game info that changes) //=============================|================================================ uint256 public airDropPot_; // person who gets the airdrop wins part of this pot uint256 public airDropTracker_ = 0; // incremented each time a "qualified" tx occurs. used to determine winning air drop uint256 public rID_; // round id number / total rounds that have happened //**************** // PLAYER DATA //**************** mapping (address => uint256) public pIDxAddr_; // (addr => pID) returns player id by address mapping (bytes32 => uint256) public pIDxName_; // (name => pID) returns player id by name mapping (uint256 => CAE4Ddatasets.Player) public plyr_; // (pID => data) player data mapping (uint256 => mapping (uint256 => CAE4Ddatasets.PlayerRounds)) public plyrRnds_; // (pID => rID => data) player round data by player id & round id mapping (uint256 => mapping (bytes32 => bool)) public plyrNames_; // (pID => name => bool) list of names a player owns. (used so you can change your display name amongst any name you own) //**************** // ROUND DATA //**************** mapping (uint256 => CAE4Ddatasets.Round) public round_; // (rID => data) round data mapping (uint256 => mapping(uint256 => uint256)) public rndTmEth_; // (rID => tID => data) eth in per team, by round id and team id //**************** // TEAM FEE DATA //**************** mapping (uint256 => CAE4Ddatasets.TeamFee) public fees_; // (team => fees) fee distribution by team mapping (uint256 => CAE4Ddatasets.PotSplit) public potSplit_; // (team => fees) pot split distribution by team //============================================================================== // _ _ _ __|_ _ __|_ _ _ . // (_(_)| |_\ | | |_|(_ | (_)| . (initial data setup upon contract deploy) //============================================================================== //constructor(address addr1,address addr2) constructor() public { //playerbookaddr = addr2; //jekylladdr = addr1; //DiviesInterface constant private Divies = DiviesInterface(0xc7029Ed9EBa97A096e72607f4340c34049C7AF48); //Jekyll_Island_Inc = JIincForwarderInterface(jekylladdr); //PlayerBook = PlayerBookInterface(playerbookaddr); // Team allocation structures // 0 = elephants // 1 = nuts // 2 = rock // 3 = rivulets // Team allocation percentages // (Gen,Pot,Referrals,Community) // Referrals / Community rewards are mathematically designed to come from the winner's share of the pot. fees_[0] = CAE4Ddatasets.TeamFee(20,60,15,5); //60% to pot, 15% to aff, 5% to com fees_[1] = CAE4Ddatasets.TeamFee(41,24,30,5); //24% to pot, 30% to aff, 5% to com fees_[2] = CAE4Ddatasets.TeamFee(55,30,10,5); //30% to pot, 10% to aff, 5% to com fees_[3] = CAE4Ddatasets.TeamFee(50,20,25,5); //20% to pot, 25% to aff, 5% to com // how to split up the final pot based on which team was picked // (gen,win,next,com) potSplit_[0] = CAE4Ddatasets.PotSplit(10,75,13,2); //75% to winner, 13% to next round, 2% to com potSplit_[1] = CAE4Ddatasets.PotSplit(20,65,13,2); //65% to winner, 13% to next round, 2% to com potSplit_[2] = CAE4Ddatasets.PotSplit(25,65,8,2); //65% to winner, 8% to next round, 2% to com potSplit_[3] = CAE4Ddatasets.PotSplit(40,45,13,2); //45% to winner, 13% to next round, 2% to com } //============================================================================== // _ _ _ _|. |`. _ _ _ . // | | |(_)(_||~|~|(/_| _\ . (these are safety checks) //============================================================================== /** * @dev used to make sure no one can interact with contract until it has * been activated. */ modifier isActivated() { require(activated_ == true, "its not ready yet. check ?eta in discord"); _; } /** * @dev prevents contracts from interacting with fomo3d */ modifier isHuman() { address _addr = msg.sender; uint256 _codeLength; assembly {_codeLength := extcodesize(_addr)} require(_codeLength == 0, "sorry humans only"); _; } /** * @dev sets boundaries for incoming tx */ modifier isWithinLimits(uint256 _eth) { require(_eth >= 1000000000, "pocket lint: not a valid currency"); require(_eth <= 100000000000000000000000, "no vitalik, no"); _; } //============================================================================== // _ |_ |. _ |` _ __|_. _ _ _ . // |_)|_||_)||(_ ~|~|_|| |(_ | |(_)| |_\ . (use these to interact with contract) //====|========================================================================= /** * @dev emergency buy uses last stored affiliate ID and team snek */ function() isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not CAE4Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // buy core buyCore(_pID, plyr_[_pID].laff, 2, _eventData_); } /** * @dev converts all incoming ethereum to keys. * @param _affCode the ID/address/name of the player who gets the affiliate fee * @param _team what team is the player playing for? */ function buyXid(uint256 _affCode, uint256 _team) isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not CAE4Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals // if no affiliate code was given or player tried to use their own, lolz if (_affCode == 0 || _affCode == _pID) { // use last stored affiliate code _affCode = plyr_[_pID].laff; // if affiliate code was given & its not the same as previously stored } else if (_affCode != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affCode; } // verify a valid team was selected _team = verifyTeam(_team); // buy core buyCore(_pID, _affCode, _team, _eventData_); } function buyXaddr(address _affCode, uint256 _team) isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not CAE4Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == address(0) || _affCode == msg.sender) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxAddr_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // verify a valid team was selected _team = verifyTeam(_team); // buy core buyCore(_pID, _affID, _team, _eventData_); } function buyXname(bytes32 _affCode, uint256 _team) isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not CAE4Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == '' || _affCode == plyr_[_pID].name) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxName_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // verify a valid team was selected _team = verifyTeam(_team); // buy core buyCore(_pID, _affID, _team, _eventData_); } /** * @dev essentially the same as buy, but instead of you sending ether * from your wallet, it uses your unwithdrawn earnings. * @param _affCode the ID/address/name of the player who gets the affiliate fee * @param _team what team is the player playing for? * @param _eth amount of earnings to use (remainder returned to gen vault) */ function reLoadXid(uint256 _affCode, uint256 _team, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { // set up our tx event data CAE4Ddatasets.EventReturns memory _eventData_; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals // if no affiliate code was given or player tried to use their own, lolz if (_affCode == 0 || _affCode == _pID) { // use last stored affiliate code _affCode = plyr_[_pID].laff; // if affiliate code was given & its not the same as previously stored } else if (_affCode != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affCode; } // verify a valid team was selected _team = verifyTeam(_team); // reload core reLoadCore(_pID, _affCode, _team, _eth, _eventData_); } function reLoadXaddr(address _affCode, uint256 _team, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { // set up our tx event data CAE4Ddatasets.EventReturns memory _eventData_; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == address(0) || _affCode == msg.sender) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxAddr_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // verify a valid team was selected _team = verifyTeam(_team); // reload core reLoadCore(_pID, _affID, _team, _eth, _eventData_); } function reLoadXname(bytes32 _affCode, uint256 _team, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { // set up our tx event data CAE4Ddatasets.EventReturns memory _eventData_; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == '' || _affCode == plyr_[_pID].name) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxName_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // verify a valid team was selected _team = verifyTeam(_team); // reload core reLoadCore(_pID, _affID, _team, _eth, _eventData_); } /** * @dev withdraws all of your earnings. * -functionhash- 0x3ccfd60b */ function withdraw() isActivated() isHuman() public { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // setup temp var for player eth uint256 _eth; // check to see if round has ended and no one has run round end yet if (_now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0) { // set up our tx event data CAE4Ddatasets.EventReturns memory _eventData_; // end the round (distributes pot) round_[_rID].ended = true; _eventData_ = endRound(_eventData_); // get their earnings _eth = withdrawEarnings(_pID); // gib moni if (_eth > 0) plyr_[_pID].addr.transfer(_eth); // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire withdraw and distribute event emit CAE4Devents.onWithdrawAndDistribute ( msg.sender, plyr_[_pID].name, _eth, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.P3DAmount, _eventData_.genAmount ); // in any other situation } else { // get their earnings _eth = withdrawEarnings(_pID); // gib moni if (_eth > 0) plyr_[_pID].addr.transfer(_eth); // fire withdraw event emit CAE4Devents.onWithdraw(_pID, msg.sender, plyr_[_pID].name, _eth, _now); } } /** * @dev use these to register names. they are just wrappers that will send the * registration requests to the PlayerBook contract. So registering here is the * same as registering there. UI will always display the last name you registered. * but you will still own all previously registered names to use as affiliate * links. * - must pay a registration fee. * - name must be unique * - names will be converted to lowercase * - name cannot start or end with a space * - cannot have more than 1 space in a row * - cannot be only numbers * - cannot start with 0x * - name must be at least 1 char * - max length of 32 characters long * - allowed characters: a-z, 0-9, and space * @param _nameString players desired name * @param _affCode affiliate ID, address, or name of who referred you * @param _all set to true if you want this to push your info to all games * (this might cost a lot of gas) */ function registerNameXID(string _nameString, uint256 _affCode, bool _all) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXIDFromDapp.value(_paid)(_addr, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; // fire event emit CAE4Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); } function registerNameXaddr(string _nameString, address _affCode, bool _all) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXaddrFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; // fire event emit CAE4Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); } function registerNameXname(string _nameString, bytes32 _affCode, bool _all) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXnameFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; // fire event emit CAE4Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); } //============================================================================== // _ _ _|__|_ _ _ _ . // (_|(/_ | | (/_| _\ . (for UI & viewing things on etherscan) //=====_|======================================================================= /** * @dev return the price buyer will pay for next 1 individual key. * -functionhash- 0x018a25e8 * @return price for next key bought (in wei format) */ function getBuyPrice() public view returns(uint256) { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // are we in a round? if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) return ( (round_[_rID].keys.add(1000000000000000000)).ethRec(1000000000000000000) ); else // rounds over. need price for new round return ( 75000000000000 ); // init } /** * @dev returns time left. dont spam this, you'll ddos yourself from your node * provider * -functionhash- 0xc7e284b8 * @return time left in seconds */ function getTimeLeft() public view returns(uint256) { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; if (_now < round_[_rID].end) if (_now > round_[_rID].strt + rndGap_) return( (round_[_rID].end).sub(_now) ); else return( (round_[_rID].strt + rndGap_).sub(_now) ); else return(0); } /** * @dev returns player earnings per vaults * -functionhash- 0x63066434 * @return winnings vault * @return general vault * @return affiliate vault */ function getPlayerVaults(uint256 _pID) public view returns(uint256 ,uint256, uint256) { // setup local rID uint256 _rID = rID_; // if round has ended. but round end has not been run (so contract has not distributed winnings) if (now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0) { // if player is winner if (round_[_rID].plyr == _pID) { return ( (plyr_[_pID].win).add( ((round_[_rID].pot).mul(48)) / 100 ), (plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ), plyr_[_pID].aff ); // if player is not the winner } else { return ( plyr_[_pID].win, (plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ), plyr_[_pID].aff ); } // if round is still going on, or round has ended and round end has been ran } else { return ( plyr_[_pID].win, (plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), plyr_[_pID].aff ); } } /** * solidity hates stack limits. this lets us avoid that hate */ function getPlayerVaultsHelper(uint256 _pID, uint256 _rID) private view returns(uint256) { return( ((((round_[_rID].mask).add(((((round_[_rID].pot).mul(potSplit_[round_[_rID].team].gen)) / 100).mul(1000000000000000000)) / (round_[_rID].keys))).mul(plyrRnds_[_pID][_rID].keys)) / 1000000000000000000) ); } /** * @dev returns all current round info needed for front end * -functionhash- 0x747dff42 * @return eth invested during ICO phase * @return round id * @return total keys for round * @return time round ends * @return time round started * @return current pot * @return current team ID & player ID in lead * @return current player in leads address * @return current player in leads name * @return elephants eth in for round * @return nuts eth in for round * @return rock eth in for round * @return rivulets eth in for round * @return airdrop tracker # & airdrop pot */ function getCurrentRoundInfo() public view returns(uint256, uint256, uint256, uint256, uint256, uint256, uint256, address, bytes32, uint256, uint256, uint256, uint256, uint256) { // setup local rID uint256 _rID = rID_; return ( round_[_rID].eth, //0 _rID, //1 round_[_rID].keys, //2 round_[_rID].end, //3 round_[_rID].strt, //4 round_[_rID].pot, //5 (round_[_rID].team + (round_[_rID].plyr * 10)), //6 plyr_[round_[_rID].plyr].addr, //7 plyr_[round_[_rID].plyr].name, //8 rndTmEth_[_rID][0], //9 rndTmEth_[_rID][1], //10 rndTmEth_[_rID][2], //11 rndTmEth_[_rID][3], //12 airDropTracker_ + (airDropPot_ * 1000) //13 ); } function getCurrentRoundRewards() public view returns(uint256){ uint256 _rID = rID_; return (round_[_rID].eth.add(round_[_rID].initPot).sub(round_[_rID].pot)); } /** * @dev returns player info based on address. if no address is given, it will * use msg.sender * -functionhash- 0xee0b5d8b * @param _addr address of the player you want to lookup * @return player ID * @return player name * @return keys owned (current round) * @return winnings vault * @return general vault * @return affiliate vault * @return player round eth */ function getPlayerInfoByAddress(address _addr) public view returns(uint256, bytes32, uint256, uint256, uint256, uint256, uint256) { // setup local rID uint256 _rID = rID_; if (_addr == address(0)) { _addr == msg.sender; } uint256 _pID = pIDxAddr_[_addr]; return ( _pID, //0 plyr_[_pID].name, //1 plyrRnds_[_pID][_rID].keys, //2 plyr_[_pID].win, //3 (plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), //4 plyr_[_pID].aff, //5 plyrRnds_[_pID][_rID].eth //6 ); } //============================================================================== // _ _ _ _ | _ _ . _ . // (_(_)| (/_ |(_)(_||(_ . (this + tools + calcs + modules = our softwares engine) //=====================_|======================================================= /** * @dev logic runs whenever a buy order is executed. determines how to handle * incoming eth depending on if we are in an active round or not */ function buyCore(uint256 _pID, uint256 _affID, uint256 _team, CAE4Ddatasets.EventReturns memory _eventData_) private { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // if round is active if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) { // call core core(_rID, _pID, msg.value, _affID, _team, _eventData_); // if round is not active } else { // check to see if end round needs to be ran if (_now > round_[_rID].end && round_[_rID].ended == false) { // end the round (distributes pot) & start new round round_[_rID].ended = true; _eventData_ = endRound(_eventData_); // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire buy and distribute event emit CAE4Devents.onBuyAndDistribute ( msg.sender, plyr_[_pID].name, msg.value, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.P3DAmount, _eventData_.genAmount ); } // put eth in players vault plyr_[_pID].gen = plyr_[_pID].gen.add(msg.value); } } /** * @dev logic runs whenever a reload order is executed. determines how to handle * incoming eth depending on if we are in an active round or not */ function reLoadCore(uint256 _pID, uint256 _affID, uint256 _team, uint256 _eth, CAE4Ddatasets.EventReturns memory _eventData_) private { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // if round is active if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) { // get earnings from all vaults and return unused to gen vault // because we use a custom safemath library. this will throw if player // tried to spend more eth than they have. plyr_[_pID].gen = withdrawEarnings(_pID).sub(_eth); // call core core(_rID, _pID, _eth, _affID, _team, _eventData_); // if round is not active and end round needs to be ran } else if (_now > round_[_rID].end && round_[_rID].ended == false) { // end the round (distributes pot) & start new round round_[_rID].ended = true; _eventData_ = endRound(_eventData_); // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire buy and distribute event emit CAE4Devents.onReLoadAndDistribute ( msg.sender, plyr_[_pID].name, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.P3DAmount, _eventData_.genAmount ); } } /** * @dev this is the core logic for any buy/reload that happens while a round * is live. */ function core(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, CAE4Ddatasets.EventReturns memory _eventData_) private { // if player is new to round if (plyrRnds_[_pID][_rID].keys == 0) _eventData_ = managePlayer(_pID, _eventData_); // early round eth limiter //if (round_[_rID].eth < 100000000000000000000 && plyrRnds_[_pID][_rID].eth.add(_eth) > 5000000000000000000) //{ // uint256 _availableLimit = (5000000000000000000).sub(plyrRnds_[_pID][_rID].eth); // uint256 _refund = _eth.sub(_availableLimit); // plyr_[_pID].gen = plyr_[_pID].gen.add(_refund); // _eth = _availableLimit; //} // if eth left is greater than min eth allowed (sorry no pocket lint) if (_eth > 1000000000) { // mint the new keys uint256 _keys = (round_[_rID].eth).keysRec(_eth); // if they bought at least 1 whole key if (_keys >= 1000000000000000000) { updateTimer(_keys, _rID); // set new leaders if (round_[_rID].plyr != _pID) round_[_rID].plyr = _pID; if (round_[_rID].team != _team) round_[_rID].team = _team; // set the new leader bool to true _eventData_.compressedData = _eventData_.compressedData + 100; } // manage airdrops if (_eth >= 100000000000000000) { airDropTracker_++; if (airdrop() == true) { // gib muni uint256 _prize; if (_eth >= 10000000000000000000) { // calculate prize and give it to winner _prize = ((airDropPot_).mul(75)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize); // adjust airDropPot airDropPot_ = (airDropPot_).sub(_prize); // let event know a tier 3 prize was won _eventData_.compressedData += 300000000000000000000000000000000; } else if (_eth >= 1000000000000000000 && _eth < 10000000000000000000) { // calculate prize and give it to winner _prize = ((airDropPot_).mul(50)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize); // adjust airDropPot airDropPot_ = (airDropPot_).sub(_prize); // let event know a tier 2 prize was won _eventData_.compressedData += 200000000000000000000000000000000; } else if (_eth >= 100000000000000000 && _eth < 1000000000000000000) { // calculate prize and give it to winner _prize = ((airDropPot_).mul(25)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize); // adjust airDropPot airDropPot_ = (airDropPot_).sub(_prize); // let event know a tier 3 prize was won _eventData_.compressedData += 300000000000000000000000000000000; } // set airdrop happened bool to true _eventData_.compressedData += 10000000000000000000000000000000; // let event know how much was won _eventData_.compressedData += _prize * 1000000000000000000000000000000000; // reset air drop tracker airDropTracker_ = 0; } } // store the air drop tracker number (number of buys since last airdrop) _eventData_.compressedData = _eventData_.compressedData + (airDropTracker_ * 1000); // update player plyrRnds_[_pID][_rID].keys = _keys.add(plyrRnds_[_pID][_rID].keys); plyrRnds_[_pID][_rID].eth = _eth.add(plyrRnds_[_pID][_rID].eth); // update round round_[_rID].keys = _keys.add(round_[_rID].keys); round_[_rID].eth = _eth.add(round_[_rID].eth); rndTmEth_[_rID][_team] = _eth.add(rndTmEth_[_rID][_team]); // distribute eth _eventData_ = distributeExternal(_rID, _pID, _eth, _affID, _team, _eventData_); _eventData_ = distributeInternal(_rID, _pID, _eth, _team, _keys, _eventData_); // call end tx function to fire end tx event. endTx(_pID, _team, _eth, _keys, _eventData_); } } //============================================================================== // _ _ | _ | _ _|_ _ _ _ . // (_(_||(_|_||(_| | (_)| _\ . //============================================================================== /** * @dev calculates unmasked earnings (just calculates, does not update mask) * @return earnings in wei format */ function calcUnMaskedEarnings(uint256 _pID, uint256 _rIDlast) private view returns(uint256) { return( (((round_[_rIDlast].mask).mul(plyrRnds_[_pID][_rIDlast].keys)) / (1000000000000000000)).sub(plyrRnds_[_pID][_rIDlast].mask) ); } /** * @dev returns the amount of keys you would get given an amount of eth. * -functionhash- 0xce89c80c * @param _rID round ID you want price for * @param _eth amount of eth sent in * @return keys received */ function calcKeysReceived(uint256 _rID, uint256 _eth) public view returns(uint256) { // grab time uint256 _now = now; // are we in a round? if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) return ( (round_[_rID].eth).keysRec(_eth) ); else // rounds over. need keys for new round return ( (_eth).keys() ); } /** * @dev returns current eth price for X keys. * -functionhash- 0xcf808000 * @param _keys number of keys desired (in 18 decimal format) * @return amount of eth needed to send */ function iWantXKeys(uint256 _keys) public view returns(uint256) { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // are we in a round? if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) return ( (round_[_rID].keys.add(_keys)).ethRec(_keys) ); else // rounds over. need price for new round return ( (_keys).eth() ); } //============================================================================== // _|_ _ _ | _ . // | (_)(_)|_\ . //============================================================================== /** * @dev receives name/player info from names contract */ function receivePlayerInfo(uint256 _pID, address _addr, bytes32 _name, uint256 _laff) external { require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm.."); if (pIDxAddr_[_addr] != _pID) pIDxAddr_[_addr] = _pID; if (pIDxName_[_name] != _pID) pIDxName_[_name] = _pID; if (plyr_[_pID].addr != _addr) plyr_[_pID].addr = _addr; if (plyr_[_pID].name != _name) plyr_[_pID].name = _name; if (plyr_[_pID].laff != _laff) plyr_[_pID].laff = _laff; if (plyrNames_[_pID][_name] == false) plyrNames_[_pID][_name] = true; } /** * @dev receives entire player name list */ function receivePlayerNameList(uint256 _pID, bytes32 _name) external { require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm.."); if(plyrNames_[_pID][_name] == false) plyrNames_[_pID][_name] = true; } /** * @dev gets existing or registers new pID. use this when a player may be new * @return pID */ function determinePID(CAE4Ddatasets.EventReturns memory _eventData_) private returns (CAE4Ddatasets.EventReturns) { uint256 _pID = pIDxAddr_[msg.sender]; // if player is new to this version of fomo3d if (_pID == 0) { // grab their player ID, name and last aff ID, from player names contract _pID = PlayerBook.getPlayerID(msg.sender); bytes32 _name = PlayerBook.getPlayerName(_pID); uint256 _laff = PlayerBook.getPlayerLAff(_pID); // set up player account pIDxAddr_[msg.sender] = _pID; plyr_[_pID].addr = msg.sender; if (_name != "") { pIDxName_[_name] = _pID; plyr_[_pID].name = _name; plyrNames_[_pID][_name] = true; } if (_laff != 0 && _laff != _pID) plyr_[_pID].laff = _laff; // set the new player bool to true _eventData_.compressedData = _eventData_.compressedData + 1; } return (_eventData_); } /** * @dev checks to make sure user picked a valid team. if not sets team * to default (rock) */ function verifyTeam(uint256 _team) private pure returns (uint256) { if (_team < 0 || _team > 3) return(2); else return(_team); } /** * @dev decides if round end needs to be run & new round started. and if * player unmasked earnings from previously played rounds need to be moved. */ function managePlayer(uint256 _pID, CAE4Ddatasets.EventReturns memory _eventData_) private returns (CAE4Ddatasets.EventReturns) { // if player has played a previous round, move their unmasked earnings // from that round to gen vault. if (plyr_[_pID].lrnd != 0) updateGenVault(_pID, plyr_[_pID].lrnd); // update player's last round played plyr_[_pID].lrnd = rID_; // set the joined round bool to true _eventData_.compressedData = _eventData_.compressedData + 10; return(_eventData_); } /** * @dev ends the round. manages paying out winner/splitting up pot */ function endRound(CAE4Ddatasets.EventReturns memory _eventData_) private returns (CAE4Ddatasets.EventReturns) { // setup local rID uint256 _rID = rID_; // grab our winning player and team id's uint256 _winPID = round_[_rID].plyr; uint256 _winTID = round_[_rID].team; // grab our pot amount uint256 _pot = round_[_rID].pot; // calculate our winner share, community rewards, gen share, // p3d share, and amount reserved for next pot uint256 _win = (_pot.mul(potSplit_[_winTID].win)) / 100; uint256 _com = (_pot.mul(potSplit_[_winTID].com)) / 100; uint256 _gen = (_pot.mul(potSplit_[_winTID].gen)) / 100; uint256 _res = ((_pot.sub(_win)).sub(_com)).sub(_gen); // calculate ppt for round mask uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys); uint256 _dust = _gen.sub((_ppt.mul(round_[_rID].keys)) / 1000000000000000000); if (_dust > 0) { _gen = _gen.sub(_dust); _res = _res.add(_dust); } // pay our winner plyr_[_winPID].win = _win.add(plyr_[_winPID].win); // community rewards if (!address(Jekyll_Island_Inc).call.value(_com)(bytes4(keccak256("deposit()")))) { // This ensures Team Just cannot influence the outcome of FoMo3D with // bank migrations by breaking outgoing transactions. // Something we would never do. But that's not the point. // We spent 2000$ in eth re-deploying just to patch this, we hold the // highest belief that everything we create should be trustless. // Team JUST, The name you shouldn't have to trust. //_p3d = _p3d.add(_com); _res = _res.add(_com); _com = 0; } // distribute gen portion to key holders round_[_rID].mask = _ppt.add(round_[_rID].mask); // send share for p3d to divies //if (_p3d > 0) //Divies.deposit.value(_p3d)(); // prepare event data _eventData_.compressedData = _eventData_.compressedData + (round_[_rID].end * 1000000); _eventData_.compressedIDs = _eventData_.compressedIDs + (_winPID * 100000000000000000000000000) + (_winTID * 100000000000000000); _eventData_.winnerAddr = plyr_[_winPID].addr; _eventData_.winnerName = plyr_[_winPID].name; _eventData_.amountWon = _win; _eventData_.genAmount = _gen; //_eventData_.P3DAmount = _p3d; _eventData_.newPot = _res; // start next round rID_++; _rID++; round_[_rID].strt = now; round_[_rID].end = now.add(rndInit_).add(rndGap_); round_[_rID].pot = _res; round_[_rID].initPot = round_[_rID].pot; return(_eventData_); } /** * @dev moves any unmasked earnings to gen vault. updates earnings mask */ function updateGenVault(uint256 _pID, uint256 _rIDlast) private { uint256 _earnings = calcUnMaskedEarnings(_pID, _rIDlast); if (_earnings > 0) { // put in gen vault plyr_[_pID].gen = _earnings.add(plyr_[_pID].gen); // zero out their earnings by updating mask plyrRnds_[_pID][_rIDlast].mask = _earnings.add(plyrRnds_[_pID][_rIDlast].mask); } } /** * @dev updates round timer based on number of whole keys bought. */ function updateTimer(uint256 _keys, uint256 _rID) private { // grab time uint256 _now = now; // calculate time based on number of keys bought uint256 _newTime; if (_now > round_[_rID].end && round_[_rID].plyr == 0) _newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(_now); else _newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(round_[_rID].end); // compare to max and set new end time if (_newTime < (rndMax_).add(_now)) round_[_rID].end = _newTime; else round_[_rID].end = rndMax_.add(_now); } /** * @dev generates a random number between 0-99 and checks to see if thats * resulted in an airdrop win * @return do we have a winner? */ function airdrop() private view returns(bool) { uint256 seed = uint256(keccak256(abi.encodePacked( (block.timestamp).add (block.difficulty).add ((uint256(keccak256(abi.encodePacked(block.coinbase)))) / (now)).add (block.gaslimit).add ((uint256(keccak256(abi.encodePacked(msg.sender)))) / (now)).add (block.number) ))); if((seed - ((seed / 1000) * 1000)) < airDropTracker_) return(true); else return(false); } /** * @dev distributes eth based on fees to com, aff, and p3d * CAE4Ddatasets.TeamFee(20,0); //60% to pot, 15% to aff, 5% to com */ function distributeExternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, CAE4Ddatasets.EventReturns memory _eventData_) private returns(CAE4Ddatasets.EventReturns) { // pay x% out to community rewards uint256 _com = _eth.mul(fees_[_team].com) / 100; // distribute share to affiliate uint256 _aff = _eth.mul(fees_[_team].aff) / 100; // decide what to do with affiliate share of fees // affiliate must not be self, and must have a name registered if (_affID != _pID && plyr_[_affID].name != '') { plyr_[_affID].aff = _aff.add(plyr_[_affID].aff); emit CAE4Devents.onAffiliatePayout(_affID, plyr_[_affID].addr, plyr_[_affID].name, _rID, _pID, _aff, now); } else { _com = _com.add(_aff); //_p3d = _aff; } if (!address(Jekyll_Island_Inc).call.value(_com)(bytes4(keccak256("deposit()")))) { // This ensures Team Just cannot influence the outcome of FoMo3D with // bank migrations by breaking outgoing transactions. // Something we would never do. But that's not the point. // We spent 2000$ in eth re-deploying just to patch this, we hold the // highest belief that everything we create should be trustless. // Team JUST, The name you shouldn't have to trust. //_p3d = _com; round_[rID_].pot = round_[rID_].pot.add(_com); _com = 0; } // pay out p3d //_p3d = _p3d.add((_eth.mul(fees_[_team].p3d)) / (100)); //if (_p3d > 0) //{ // deposit to divies contract //Divies.deposit.value(_p3d)(); // set up event data // _eventData_.P3DAmount = _p3d.add(_eventData_.P3DAmount); //} return(_eventData_); } function potSwap() external payable { // setup local rID uint256 _rID = rID_ + 1; round_[_rID].pot = round_[_rID].pot.add(msg.value); emit CAE4Devents.onPotSwapDeposit(_rID, msg.value); } /** * @dev distributes eth based on fees to gen and pot */ function distributeInternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _team, uint256 _keys, CAE4Ddatasets.EventReturns memory _eventData_) private returns(CAE4Ddatasets.EventReturns) { // calculate gen share uint256 _gen = (_eth.mul(fees_[_team].gen)) / 100; // toss 1% into airdrop pot //uint256 _air = (_eth / 100); //airDropPot_ = airDropPot_.add(_air); // update eth balance (eth = eth - (com share + pot swap share + aff share + p3d share + airdrop pot share)) //_eth = _eth.sub(((14) / 100).add((_eth.mul(fees_[_team].p3d)) / 100)); _eth = _eth.sub((_eth.mul(fees_[_team].com + fees_[_team].aff)) / 100); // calculate pot uint256 _pot = _eth.sub(_gen); // distribute gen share (thats what updateMasks() does) and adjust // balances for dust. uint256 _dust = updateMasks(_rID, _pID, _gen, _keys); if (_dust > 0) _gen = _gen.sub(_dust); // add eth to pot round_[_rID].pot = _pot.add(_dust).add(round_[_rID].pot); // set up event data _eventData_.genAmount = _gen.add(_eventData_.genAmount); _eventData_.potAmount = _pot; return(_eventData_); } /** * @dev updates masks for round and player when keys are bought * @return dust left over */ function updateMasks(uint256 _rID, uint256 _pID, uint256 _gen, uint256 _keys) private returns(uint256) { /* MASKING NOTES earnings masks are a tricky thing for people to wrap their minds around. the basic thing to understand here. is were going to have a global tracker based on profit per share for each round, that increases in relevant proportion to the increase in share supply. the player will have an additional mask that basically says "based on the rounds mask, my shares, and how much i've already withdrawn, how much is still owed to me?" */ // calc profit per key & round mask based on this buy: (dust goes to pot) uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys); round_[_rID].mask = _ppt.add(round_[_rID].mask); // calculate player earning from their own buy (only based on the keys // they just bought). & update player earnings mask uint256 _pearn = (_ppt.mul(_keys)) / (1000000000000000000); plyrRnds_[_pID][_rID].mask = (((round_[_rID].mask.mul(_keys)) / (1000000000000000000)).sub(_pearn)).add(plyrRnds_[_pID][_rID].mask); // calculate & return dust return(_gen.sub((_ppt.mul(round_[_rID].keys)) / (1000000000000000000))); } /** * @dev adds up unmasked earnings, & vault earnings, sets them all to 0 * @return earnings in wei format */ function withdrawEarnings(uint256 _pID) private returns(uint256) { // update gen vault updateGenVault(_pID, plyr_[_pID].lrnd); // from vaults uint256 _earnings = (plyr_[_pID].win).add(plyr_[_pID].gen).add(plyr_[_pID].aff); if (_earnings > 0) { plyr_[_pID].win = 0; plyr_[_pID].gen = 0; plyr_[_pID].aff = 0; } return(_earnings); } /** * @dev prepares compression data and fires event for buy or reload tx's */ function endTx(uint256 _pID, uint256 _team, uint256 _eth, uint256 _keys, CAE4Ddatasets.EventReturns memory _eventData_) private { _eventData_.compressedData = _eventData_.compressedData + (now * 1000000000000000000) + (_team * 100000000000000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID + (rID_ * 10000000000000000000000000000000000000000000000000000); emit CAE4Devents.onEndTx ( _eventData_.compressedData, _eventData_.compressedIDs, plyr_[_pID].name, msg.sender, _eth, _keys, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.P3DAmount, _eventData_.genAmount, _eventData_.potAmount, airDropPot_ ); } //============================================================================== // (~ _ _ _._|_ . // _)(/_(_|_|| | | \/ . //====================/========================================================= /** upon contract deploy, it will be deactivated. this is a one time * use function that will activate the contract. we do this so devs * have time to set things up on the web end **/ bool public activated_ = false; function activate() public { // only team just can activate require( msg.sender == 0xe1A375cd31baF61D2fDAbd93F85c22A49a3795aF || msg.sender == 0xbD63f951D2FbbA361b2B48F65fce7E227EFD0CAC , "only team just can activate" ); // can only be ran once require(activated_ == false, "fomo3d already activated"); // activate the contract activated_ = true; // lets start first round rID_ = 1; round_[1].strt = now + rndExtra_ - rndGap_; round_[1].end = now + rndInit_ + rndExtra_; } } library NameFilter { /** * @dev filters name strings * -converts uppercase to lower case. * -makes sure it does not start/end with a space * -makes sure it does not contain multiple spaces in a row * -cannot be only numbers * -cannot start with 0x * -restricts characters to A-Z, a-z, 0-9, and space. * @return reprocessed string in bytes32 format */ function nameFilter(string _input) internal pure returns(bytes32) { bytes memory _temp = bytes(_input); uint256 _length = _temp.length; //sorry limited to 32 characters require (_length <= 32 && _length > 0, "string must be between 1 and 32 characters"); // make sure it doesnt start with or end with space require(_temp[0] != 0x20 && _temp[_length-1] != 0x20, "string cannot start or end with space"); // make sure first two characters are not 0x if (_temp[0] == 0x30) { require(_temp[1] != 0x78, "string cannot start with 0x"); require(_temp[1] != 0x58, "string cannot start with 0X"); } // create a bool to track if we have a non number character bool _hasNonNumber; // convert & check for (uint256 i = 0; i < _length; i++) { // if its uppercase A-Z if (_temp[i] > 0x40 && _temp[i] < 0x5b) { // convert to lower case a-z _temp[i] = byte(uint(_temp[i]) + 32); // we have a non number if (_hasNonNumber == false) _hasNonNumber = true; } else { require ( // require character is a space _temp[i] == 0x20 || // OR lowercase a-z (_temp[i] > 0x60 && _temp[i] < 0x7b) || // or 0-9 (_temp[i] > 0x2f && _temp[i] < 0x3a), "string contains invalid characters" ); // make sure theres not 2x spaces in a row if (_temp[i] == 0x20) require( _temp[i+1] != 0x20, "string cannot contain consecutive spaces"); // see if we have a character other than a number if (_hasNonNumber == false && (_temp[i] < 0x30 || _temp[i] > 0x39)) _hasNonNumber = true; } } require(_hasNonNumber == true, "string cannot be only numbers"); bytes32 _ret; assembly { _ret := mload(add(_temp, 32)) } return (_ret); } } library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; require(c / a == b, "SafeMath mul failed"); return c; } /** * @dev 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) { require(b <= a, "SafeMath sub failed"); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; require(c >= a, "SafeMath add failed"); return c; } /** * @dev gives square root of given x. */ function sqrt(uint256 x) internal pure returns (uint256 y) { uint256 z = ((add(x,1)) / 2); y = x; while (z < y) { y = z; z = ((add((x / z),z)) / 2); } } /** * @dev gives square. multiplies x by x */ function sq(uint256 x) internal pure returns (uint256) { return (mul(x,x)); } /** * @dev x to the power of y */ function pwr(uint256 x, uint256 y) internal pure returns (uint256) { if (x==0) return (0); else if (y==0) return (1); else { uint256 z = x; for (uint256 i=1; i < y; i++) z = mul(z,x); return (z); } } } library UintCompressor { using SafeMath for *; function insert(uint256 _var, uint256 _include, uint256 _start, uint256 _end) internal pure returns(uint256) { // check conditions require(_end < 77 && _start < 77, "start/end must be less than 77"); require(_end >= _start, "end must be >= start"); // format our start/end points _end = exponent(_end).mul(10); _start = exponent(_start); // check that the include data fits into its segment require(_include < (_end / _start)); // build middle if (_include > 0) _include = _include.mul(_start); return((_var.sub((_var / _start).mul(_start))).add(_include).add((_var / _end).mul(_end))); } function extract(uint256 _input, uint256 _start, uint256 _end) internal pure returns(uint256) { // check conditions require(_end < 77 && _start < 77, "start/end must be less than 77"); require(_end >= _start, "end must be >= start"); // format our start/end points _end = exponent(_end).mul(10); _start = exponent(_start); // return requested section return((((_input / _start).mul(_start)).sub((_input / _end).mul(_end))) / _start); } function exponent(uint256 _position) private pure returns(uint256) { return((10).pwr(_position)); } } library CAE4DKeysCalcLong { using SafeMath for *; /** * @dev calculates number of keys received given X eth * @param _curEth current amount of eth in contract * @param _newEth eth being spent * @return amount of ticket purchased */ function keysRec(uint256 _curEth, uint256 _newEth) internal pure returns (uint256) { return(keys((_curEth).add(_newEth)).sub(keys(_curEth))); } /** * @dev calculates amount of eth received if you sold X keys * @param _curKeys current amount of keys that exist * @param _sellKeys amount of keys you wish to sell * @return amount of eth received */ function ethRec(uint256 _curKeys, uint256 _sellKeys) internal pure returns (uint256) { return((eth(_curKeys)).sub(eth(_curKeys.sub(_sellKeys)))); } /** * @dev calculates how many keys would exist with given an amount of eth * @param _eth eth "in contract" * @return number of keys that would exist */ function keys(uint256 _eth) internal pure returns(uint256) { return ((((((_eth).mul(1000000000000000000)).mul(312500000000000000000000000)).add(5624988281256103515625000000000000000000000000000000000000000000)).sqrt()).sub(74999921875000000000000000000000)) / (156250000); } /** * @dev calculates how much eth would be in contract given a number of keys * @param _keys number of keys "in contract" * @return eth that would exists */ function eth(uint256 _keys) internal pure returns(uint256) { return ((78125000).mul(_keys.sq()).add(((149999843750000).mul(_keys.mul(1000000000000000000))) / (2))) / ((1000000000000000000).sq()); } }
* @dev withdraws all of your earnings. -functionhash- 0x3ccfd60b/ setup local rID grab time fetch player ID setup temp var for player eth check to see if round has ended and no one has run round end yet set up our tx event data end the round (distributes pot) get their earnings gib moni build event data fire withdraw and distribute event in any other situation get their earnings gib moni fire withdraw event
function withdraw() isActivated() isHuman() public { uint256 _rID = rID_; uint256 _now = now; uint256 _pID = pIDxAddr_[msg.sender]; uint256 _eth; if (_now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0) { CAE4Ddatasets.EventReturns memory _eventData_; round_[_rID].ended = true; _eventData_ = endRound(_eventData_); _eth = withdrawEarnings(_pID); if (_eth > 0) plyr_[_pID].addr.transfer(_eth); _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; emit CAE4Devents.onWithdrawAndDistribute ( msg.sender, plyr_[_pID].name, _eth, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.P3DAmount, _eventData_.genAmount ); _eth = withdrawEarnings(_pID); if (_eth > 0) plyr_[_pID].addr.transfer(_eth); emit CAE4Devents.onWithdraw(_pID, msg.sender, plyr_[_pID].name, _eth, _now); } }
12,043,152
[ 1, 1918, 9446, 87, 777, 434, 3433, 425, 1303, 899, 18, 300, 915, 2816, 17, 374, 92, 23, 952, 8313, 4848, 70, 19, 3875, 1191, 436, 734, 11086, 813, 2158, 7291, 1599, 3875, 1906, 569, 364, 7291, 13750, 866, 358, 2621, 309, 3643, 711, 16926, 471, 1158, 1245, 711, 1086, 3643, 679, 4671, 444, 731, 3134, 2229, 871, 501, 679, 326, 3643, 261, 2251, 1141, 5974, 13, 336, 3675, 425, 1303, 899, 314, 495, 6921, 77, 1361, 871, 501, 4452, 598, 9446, 471, 25722, 871, 316, 1281, 1308, 20886, 336, 3675, 425, 1303, 899, 314, 495, 6921, 77, 4452, 598, 9446, 871, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 598, 9446, 1435, 203, 3639, 353, 28724, 1435, 203, 3639, 27803, 6925, 1435, 203, 3639, 1071, 203, 565, 288, 203, 3639, 2254, 5034, 389, 86, 734, 273, 436, 734, 67, 31, 203, 540, 203, 3639, 2254, 5034, 389, 3338, 273, 2037, 31, 203, 540, 203, 3639, 2254, 5034, 389, 84, 734, 273, 293, 734, 92, 3178, 67, 63, 3576, 18, 15330, 15533, 203, 540, 203, 3639, 2254, 5034, 389, 546, 31, 203, 540, 203, 3639, 309, 261, 67, 3338, 405, 3643, 67, 63, 67, 86, 734, 8009, 409, 597, 3643, 67, 63, 67, 86, 734, 8009, 3934, 422, 629, 597, 3643, 67, 63, 67, 86, 734, 8009, 1283, 86, 480, 374, 13, 203, 3639, 288, 203, 5411, 6425, 41, 24, 40, 21125, 18, 1133, 1356, 3778, 389, 2575, 751, 67, 31, 203, 2398, 203, 1082, 202, 2260, 67, 63, 67, 86, 734, 8009, 3934, 273, 638, 31, 203, 5411, 389, 2575, 751, 67, 273, 679, 11066, 24899, 2575, 751, 67, 1769, 203, 2398, 203, 5411, 389, 546, 273, 598, 9446, 41, 1303, 899, 24899, 84, 734, 1769, 203, 2398, 203, 5411, 309, 261, 67, 546, 405, 374, 13, 203, 7734, 293, 715, 86, 67, 63, 67, 84, 734, 8009, 4793, 18, 13866, 24899, 546, 1769, 377, 203, 2398, 203, 5411, 389, 2575, 751, 27799, 15385, 751, 273, 389, 2575, 751, 27799, 15385, 751, 397, 261, 67, 3338, 380, 2130, 12648, 12648, 1769, 203, 5411, 389, 2575, 751, 27799, 15385, 5103, 273, 389, 2575, 751, 27799, 15385, 5103, 397, 389, 84, 734, 31, 2 ]
pragma solidity ^0.4.24; /** @title -MSFun- v0.2.4 * * ┌──────────────────────────────────────────────────────────────────────┐ * │ MSFun, is an importable library that gives your contract the ability │ * │ add multiSig requirement to functions. │ * └──────────────────────────────────────────────────────────────────────┘ * ┌────────────────────┐ * │ Setup Instructions │ * └────────────────────┘ * (Step 1) import the library into your contract * * import "./MSFun.sol"; * * (Step 2) set up the signature data for msFun * * MSFun.Data private msData; * ┌────────────────────┐ * │ Usage Instructions │ * └────────────────────┘ * at the beginning of a function * * function functionName() * { * if (MSFun.multiSig(msData, required signatures, "functionName") == true) * { * MSFun.deleteProposal(msData, "functionName"); * * // put function body here * } * } * ┌────────────────────────────────┐ * │ Optional Wrappers For TeamJust │ * └────────────────────────────────┘ * multiSig wrapper function (cuts down on inputs, improves readability) * this wrapper is HIGHLY recommended * * function multiSig(bytes32 _whatFunction) private returns (bool) {return(MSFun.multiSig(msData, TeamJust.requiredSignatures(), _whatFunction));} * function multiSigDev(bytes32 _whatFunction) private returns (bool) {return(MSFun.multiSig(msData, TeamJust.requiredDevSignatures(), _whatFunction));} * * wrapper for delete proposal (makes code cleaner) * * function deleteProposal(bytes32 _whatFunction) private {MSFun.deleteProposal(msData, _whatFunction);} * ┌────────────────────────────┐ * │ Utility & Vanity Functions │ * └────────────────────────────┘ * delete any proposal is highly recommended. without it, if an admin calls a multiSig * function, with argument inputs that the other admins do not agree upon, the function * can never be executed until the undesirable arguments are approved. * * function deleteAnyProposal(bytes32 _whatFunction) onlyDevs() public {MSFun.deleteProposal(msData, _whatFunction);} * * for viewing who has signed a proposal & proposal data * * function checkData(bytes32 _whatFunction) onlyAdmins() public view returns(bytes32, uint256) {return(MSFun.checkMsgData(msData, _whatFunction), MSFun.checkCount(msData, _whatFunction));} * * lets you check address of up to 3 signers (address) * * function checkSignersByAddress(bytes32 _whatFunction, uint256 _signerA, uint256 _signerB, uint256 _signerC) onlyAdmins() public view returns(address, address, address) {return(MSFun.checkSigner(msData, _whatFunction, _signerA), MSFun.checkSigner(msData, _whatFunction, _signerB), MSFun.checkSigner(msData, _whatFunction, _signerC));} * * same as above but will return names in string format. * * function checkSignersByName(bytes32 _whatFunction, uint256 _signerA, uint256 _signerB, uint256 _signerC) onlyAdmins() public view returns(bytes32, bytes32, bytes32) {return(TeamJust.adminName(MSFun.checkSigner(msData, _whatFunction, _signerA)), TeamJust.adminName(MSFun.checkSigner(msData, _whatFunction, _signerB)), TeamJust.adminName(MSFun.checkSigner(msData, _whatFunction, _signerC)));} * ┌──────────────────────────┐ * │ Functions In Depth Guide │ * └──────────────────────────┘ * In the following examples, the Data is the proposal set for this library. And * the bytes32 is the name of the function. * * MSFun.multiSig(Data, uint256, bytes32) - Manages creating/updating multiSig * proposal for the function being called. The uint256 is the required * number of signatures needed before the multiSig will return true. * Upon first call, multiSig will create a proposal and store the arguments * passed with the function call as msgData. Any admins trying to sign the * function call will need to send the same argument values. Once required * number of signatures is reached this will return a bool of true. * * MSFun.deleteProposal(Data, bytes32) - once multiSig unlocks the function body, * you will want to delete the proposal data. This does that. * * MSFun.checkMsgData(Data, bytes32) - checks the message data for any given proposal * * MSFun.checkCount(Data, bytes32) - checks the number of admins that have signed * the proposal * * MSFun.checkSigners(data, bytes32, uint256) - checks the address of a given signer. * the uint256, is the log number of the signer (ie 1st signer, 2nd signer) */ library MSFun { //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // DATA SETS //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // contact data setup struct Data { mapping (bytes32 => ProposalData) proposal_; } struct ProposalData { // a hash of msg.data bytes32 msgData; // number of signers uint256 count; // tracking of wither admins have signed mapping (address => bool) admin; // list of admins who have signed mapping (uint256 => address) log; } //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // MULTI SIG FUNCTIONS //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ function multiSig(Data storage self, uint256 _requiredSignatures, bytes32 _whatFunction) internal returns(bool) { // our proposal key will be a hash of our function name + our contracts address // by adding our contracts address to this, we prevent anyone trying to circumvent // the proposal's security via external calls. bytes32 _whatProposal = whatProposal(_whatFunction); // this is just done to make the code more readable. grabs the signature count uint256 _currentCount = self.proposal_[_whatProposal].count; // store the address of the person sending the function call. we use msg.sender // here as a layer of security. in case someone imports our contract and tries to // circumvent function arguments. still though, our contract that imports this // library and calls multisig, needs to use onlyAdmin modifiers or anyone who // calls the function will be a signer. address _whichAdmin = msg.sender; // prepare our msg data. by storing this we are able to verify that all admins // are approving the same argument input to be executed for the function. we hash // it and store in bytes32 so its size is known and comparable bytes32 _msgData = keccak256(msg.data); // check to see if this is a new execution of this proposal or not if (_currentCount == 0) { // if it is, lets record the original signers data self.proposal_[_whatProposal].msgData = _msgData; // record original senders signature self.proposal_[_whatProposal].admin[_whichAdmin] = true; // update log (used to delete records later, and easy way to view signers) // also useful if the calling function wants to give something to a // specific signer. self.proposal_[_whatProposal].log[_currentCount] = _whichAdmin; // track number of signatures self.proposal_[_whatProposal].count += 1; // if we now have enough signatures to execute the function, lets // return a bool of true. we put this here in case the required signatures // is set to 1. if (self.proposal_[_whatProposal].count == _requiredSignatures) { return(true); } // if its not the first execution, lets make sure the msgData matches } else if (self.proposal_[_whatProposal].msgData == _msgData) { // msgData is a match // make sure admin hasnt already signed if (self.proposal_[_whatProposal].admin[_whichAdmin] == false) { // record their signature self.proposal_[_whatProposal].admin[_whichAdmin] = true; // update log (used to delete records later, and easy way to view signers) self.proposal_[_whatProposal].log[_currentCount] = _whichAdmin; // track number of signatures self.proposal_[_whatProposal].count += 1; } // if we now have enough signatures to execute the function, lets // return a bool of true. // we put this here for a few reasons. (1) in normal operation, if // that last recorded signature got us to our required signatures. we // need to return bool of true. (2) if we have a situation where the // required number of signatures was adjusted to at or lower than our current // signature count, by putting this here, an admin who has already signed, // can call the function again to make it return a true bool. but only if // they submit the correct msg data if (self.proposal_[_whatProposal].count == _requiredSignatures) { return(true); } } } // deletes proposal signature data after successfully executing a multiSig function function deleteProposal(Data storage self, bytes32 _whatFunction) internal { //done for readability sake bytes32 _whatProposal = whatProposal(_whatFunction); address _whichAdmin; //delete the admins votes & log. i know for loops are terrible. but we have to do this //for our data stored in mappings. simply deleting the proposal itself wouldn't accomplish this. for (uint256 i=0; i < self.proposal_[_whatProposal].count; i++) { _whichAdmin = self.proposal_[_whatProposal].log[i]; delete self.proposal_[_whatProposal].admin[_whichAdmin]; delete self.proposal_[_whatProposal].log[i]; } //delete the rest of the data in the record delete self.proposal_[_whatProposal]; } //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // HELPER FUNCTIONS //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ function whatProposal(bytes32 _whatFunction) private view returns(bytes32) { return(keccak256(abi.encodePacked(_whatFunction,this))); } //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // VANITY FUNCTIONS //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // returns a hashed version of msg.data sent by original signer for any given function function checkMsgData (Data storage self, bytes32 _whatFunction) internal view returns (bytes32 msg_data) { bytes32 _whatProposal = whatProposal(_whatFunction); return (self.proposal_[_whatProposal].msgData); } // returns number of signers for any given function function checkCount (Data storage self, bytes32 _whatFunction) internal view returns (uint256 signature_count) { bytes32 _whatProposal = whatProposal(_whatFunction); return (self.proposal_[_whatProposal].count); } // returns address of an admin who signed for any given function function checkSigner (Data storage self, bytes32 _whatFunction, uint256 _signer) internal view returns (address signer) { require(_signer > 0, "MSFun checkSigner failed - 0 not allowed"); bytes32 _whatProposal = whatProposal(_whatFunction); return (self.proposal_[_whatProposal].log[_signer - 1]); } }
deletes proposal signature data after successfully executing a multiSig functiondone for readability sakedelete the admins votes & log. i know for loops are terrible. but we have to do thisfor our data stored in mappings. simply deleting the proposal itself wouldn't accomplish this.
function deleteProposal(Data storage self, bytes32 _whatFunction) internal { bytes32 _whatProposal = whatProposal(_whatFunction); address _whichAdmin; for (uint256 i=0; i < self.proposal_[_whatProposal].count; i++) { _whichAdmin = self.proposal_[_whatProposal].log[i]; delete self.proposal_[_whatProposal].admin[_whichAdmin]; delete self.proposal_[_whatProposal].log[i]; } }
938,472
[ 1, 72, 5092, 14708, 3372, 501, 1839, 4985, 11274, 279, 3309, 8267, 445, 8734, 364, 855, 2967, 272, 9477, 929, 326, 31116, 19588, 473, 613, 18, 282, 277, 5055, 364, 14075, 854, 27428, 1523, 18, 225, 1496, 732, 1240, 358, 741, 333, 1884, 3134, 501, 4041, 316, 7990, 18, 225, 8616, 12993, 326, 14708, 6174, 4102, 82, 1404, 28217, 412, 1468, 333, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1430, 14592, 12, 751, 2502, 365, 16, 1731, 1578, 389, 23770, 2083, 13, 203, 3639, 2713, 203, 565, 288, 203, 3639, 1731, 1578, 389, 23770, 14592, 273, 4121, 14592, 24899, 23770, 2083, 1769, 203, 3639, 1758, 389, 12784, 4446, 31, 203, 203, 3639, 364, 261, 11890, 5034, 277, 33, 20, 31, 277, 411, 365, 18, 685, 8016, 67, 63, 67, 23770, 14592, 8009, 1883, 31, 277, 27245, 288, 203, 5411, 389, 12784, 4446, 273, 365, 18, 685, 8016, 67, 63, 67, 23770, 14592, 8009, 1330, 63, 77, 15533, 203, 5411, 1430, 365, 18, 685, 8016, 67, 63, 67, 23770, 14592, 8009, 3666, 63, 67, 12784, 4446, 15533, 203, 5411, 1430, 365, 18, 685, 8016, 67, 63, 67, 23770, 14592, 8009, 1330, 63, 77, 15533, 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 ]
/* * Kryptium House Smart Contract v.1.1.0 * Copyright © 2019 Kryptium Team <info@kryptium.io> * Author: Giannis Zarifis <jzarifis@kryptium.io> * * A decentralised betting house in the form of an Ethereum smart contract which * registers bets, escrows the amounts wagered and transfers funds following the * outcomes of the corresponding events. It can be fully autonomous or managed * and might charge a commission for its services. * * This program is free to use according the Terms of Use available at * <https://kryptium.io/terms-of-use/>. You cannot resell it or copy any * part of it or modify it without permission from the Kryptium Team. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the Terms and Conditions for more details. */ pragma solidity ^0.5.0; /** * SafeMath * Math operations with safety checks that throw on error */ contract SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { assert(b != 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } function mulByFraction(uint256 number, uint256 numerator, uint256 denominator) internal pure returns (uint256) { return div(mul(number, numerator), denominator); } } contract Owned { address public owner; constructor() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0x0)); owner = newOwner; } } /* Oracle smart contract interface */ interface OracleContract { function eventOutputs(uint eventId, uint outputId) external view returns (bool isSet, string memory title, uint possibleResultsCount, uint eventOutputType, string memory announcement, uint decimals); function owner() external view returns (address); function getEventForHousePlaceBet(uint id) external view returns (uint closeDateTime, uint freezeDateTime, bool isCancelled); function getEventOutcomeIsSet(uint eventId, uint outputId) external view returns (bool isSet); function getEventOutcome(uint eventId, uint outputId) external view returns (uint outcome); function getEventOutcomeNumeric(uint eventId, uint outputId) external view returns(uint256 outcome1, uint256 outcome2,uint256 outcome3,uint256 outcome4, uint256 outcome5, uint256 outcome6); } /* House smart contract interface */ interface HouseContract { function owner() external view returns (address); function isHouse() external view returns (bool); } /* * Kryptium House Smart Contract. */ contract House is SafeMath, Owned { //enum Category { football, basket } enum BetType { headtohead, multiuser, poolbet } enum BetEvent { placeBet, callBet, removeBet, refuteBet, settleWinnedBet, settleCancelledBet, increaseWager, cancelledByHouse } uint private betNextId; struct Bet { uint id; address oracleAddress; uint eventId; uint outputId; uint outcome; bool isOutcomeSet; uint closeDateTime; uint freezeDateTime; bool isCancelled; uint256 minimumWager; uint256 maximumWager; uint256 payoutRate; address createdBy; BetType betType; } struct HouseData { bool managed; string name; string creatorName; string countryISO; address oracleAddress; address oldOracleAddress; bool newBetsPaused; uint housePercentage; uint oraclePercentage; uint version; string shortMessage; } address public _newHouseAddress; HouseData public houseData; // This creates an array with all bets mapping (uint => Bet) public bets; //Last betting activity timestamp uint public lastBettingActivity; //Total bets uint public totalBets; //Total amount played on bets uint public totalAmountOnBets; //Total amount on Bet mapping (uint => uint256) public betTotalAmount; //Totalbets on bet mapping (uint => uint) public betTotalBets; //Bet Refutes amount mapping (uint => uint256) public betRefutedAmount; //Total amount placed on a bet forecast mapping (uint => mapping (uint => uint256)) public betForcastTotalAmount; //Player bet total amount on a Bet mapping (address => mapping (uint => uint256)) public playerBetTotalAmount; //Player bet total bets on a Bet mapping (address => mapping (uint => uint)) public playerBetTotalBets; //Player wager for a Bet.Output.Forecast mapping (address => mapping (uint => mapping (uint => uint256))) public playerBetForecastWager; //head to head bets forecasts mapping (uint => mapping (address => uint)) public headToHeadForecasts; //head to head bets max accepted forecasts mapping (uint => uint) public headToHeadMaxAcceptedForecasts; //Player output(cause or win or refund) of a bet mapping (address => mapping (uint => uint256)) public playerOutputFromBet; //Player bet Refuted mapping (address => mapping (uint => bool)) public playerBetRefuted; //Player bet Settled mapping (address => mapping (uint => bool)) public playerBetSettled; //Total bets placed by player mapping (address => uint) public totalPlayerBets; //Total amount placed for bets by player mapping (address => uint256) public totalPlayerBetsAmount; // User balances mapping (address => uint256) public balance; // Stores the house owners percentage as part per thousand mapping (address => uint) public ownerPerc; //The array of house owners address[] public owners; //The House and Oracle edge has been paid mapping (uint => bool) public housePaid; //The total remaining House amount collected from fees for Bet mapping (uint => uint256) public houseEdgeAmountForBet; //The total remaining Oracle amount collected from fees for Bet mapping (uint => uint256) public oracleEdgeAmountForBet; //The total House fees uint256 public houseTotalFees; //The total Oracle fees mapping (address => uint256) public oracleTotalFees; // Notifies clients that a new house is launched event HouseCreated(); // Notifies clients that a house data has changed event HousePropertiesUpdated(); event BetPlacedOrModified(uint id, address sender, BetEvent betEvent, uint256 amount, uint forecast, string createdBy, uint closeDateTime); event transfer(address indexed wallet, uint256 amount,bool inbound); event testevent(uint betTotalAmount, uint AcceptedWager, uint headToHeadForecastsOPEN, uint matchedANDforecast, uint matchedORforecast, uint headToHeadMaxAcceptedForecast); /** * Constructor function * Initializes House contract */ constructor(bool managed, string memory houseName, string memory houseCreatorName, string memory houseCountryISO, address oracleAddress, address[] memory ownerAddress, uint[] memory ownerPercentage, uint housePercentage,uint oraclePercentage, uint version) public { require(add(housePercentage,oraclePercentage)<1000,"House + Oracle percentage should be lower than 100%"); houseData.managed = managed; houseData.name = houseName; houseData.creatorName = houseCreatorName; houseData.countryISO = houseCountryISO; houseData.housePercentage = housePercentage; houseData.oraclePercentage = oraclePercentage; houseData.oracleAddress = oracleAddress; houseData.shortMessage = ""; houseData.newBetsPaused = true; houseData.version = version; uint ownersTotal = 0; for (uint i = 0; i<ownerAddress.length; i++) { owners.push(ownerAddress[i]); ownerPerc[ownerAddress[i]] = ownerPercentage[i]; ownersTotal += ownerPercentage[i]; } require(ownersTotal == 1000); emit HouseCreated(); } /** * Check if valid house contract */ function isHouse() public pure returns(bool response) { return true; } /** * Updates House Data function * */ function updateHouseProperties(string memory houseName, string memory houseCreatorName, string memory houseCountryISO) onlyOwner public { houseData.name = houseName; houseData.creatorName = houseCreatorName; houseData.countryISO = houseCountryISO; emit HousePropertiesUpdated(); } /** * Updates House Oracle function * */ function changeHouseOracle(address oracleAddress, uint oraclePercentage) onlyOwner public { require(add(houseData.housePercentage,oraclePercentage)<1000,"House + Oracle percentage should be lower than 100%"); if (oracleAddress != houseData.oracleAddress) { houseData.oldOracleAddress = houseData.oracleAddress; houseData.oracleAddress = oracleAddress; } houseData.oraclePercentage = oraclePercentage; emit HousePropertiesUpdated(); } /** * Updates House percentage function * */ function changeHouseEdge(uint housePercentage) onlyOwner public { require(housePercentage != houseData.housePercentage,"New percentage is identical with current"); require(add(housePercentage,houseData.oraclePercentage)<1000,"House + Oracle percentage should be lower than 100%"); houseData.housePercentage = housePercentage; emit HousePropertiesUpdated(); } function updateBetDataFromOracle(uint betId) private { if (!bets[betId].isOutcomeSet) { (bets[betId].isOutcomeSet) = OracleContract(bets[betId].oracleAddress).getEventOutcomeIsSet(bets[betId].eventId,bets[betId].outputId); if (bets[betId].isOutcomeSet) { (bets[betId].outcome) = OracleContract(bets[betId].oracleAddress).getEventOutcome(bets[betId].eventId,bets[betId].outputId); } } if (!bets[betId].isCancelled) { (bets[betId].closeDateTime, bets[betId].freezeDateTime, bets[betId].isCancelled) = OracleContract(bets[betId].oracleAddress).getEventForHousePlaceBet(bets[betId].eventId); } if (!bets[betId].isOutcomeSet && bets[betId].freezeDateTime <= now) { bets[betId].isCancelled = true; } } /** * Get the possibleResultsCount of an Event.Output as uint. * Should be changed in a future version to use an Oracle function that directly returns possibleResultsCount instead of receive the whole eventOutputs structure */ function getEventOutputMaxUint(address oracleAddress, uint eventId, uint outputId) private view returns (uint) { (bool isSet, string memory title, uint possibleResultsCount, uint eventOutputType, string memory announcement, uint decimals) = OracleContract(oracleAddress).eventOutputs(eventId,outputId); return 2 ** possibleResultsCount - 1; } function checkPayoutRate(uint256 payoutRate) public view { uint256 multBase = 10 ** 18; uint256 houseFees = houseData.housePercentage + houseData.oraclePercentage; uint256 check1 = div(multBase , (1000 - houseFees)); check1 = div(mul(100000 , check1), multBase); uint256 check2 = 10000; if (houseFees > 0) { check2 = div(multBase , houseFees); check2 = div(mul(100000 ,check2), multBase); } require(payoutRate>check1 && payoutRate<check2,"Payout rate out of accepted range"); } /* * Place a Bet */ function placeBet(uint eventId, BetType betType,uint outputId, uint forecast, uint256 wager, uint closingDateTime, uint256 minimumWager, uint256 maximumWager, uint256 payoutRate, string memory createdBy) public { require(wager>0,"Wager should be greater than zero"); require(balance[msg.sender]>=wager,"Not enough balance"); require(!houseData.newBetsPaused,"Bets are paused right now"); require(betType == BetType.headtohead || betType == BetType.poolbet,"Only poolbet and headtohead bets are implemented"); betNextId += 1; bets[betNextId].id = betNextId; bets[betNextId].oracleAddress = houseData.oracleAddress; bets[betNextId].outputId = outputId; bets[betNextId].eventId = eventId; bets[betNextId].betType = betType; bets[betNextId].createdBy = msg.sender; updateBetDataFromOracle(betNextId); require(!bets[betNextId].isCancelled,"Event has been cancelled"); require(!bets[betNextId].isOutcomeSet,"Event has already an outcome"); if (closingDateTime>0) { bets[betNextId].closeDateTime = closingDateTime; } require(bets[betNextId].closeDateTime >= now,"Close time has passed"); if (betType == BetType.poolbet) { if (minimumWager != 0) { bets[betNextId].minimumWager = minimumWager; } else { bets[betNextId].minimumWager = wager; } if (maximumWager != 0) { bets[betNextId].maximumWager = maximumWager; } } else if (betType == BetType.headtohead) { checkPayoutRate(payoutRate); uint maxAcceptedForecast = getEventOutputMaxUint(bets[betNextId].oracleAddress, bets[betNextId].eventId, bets[betNextId].outputId); headToHeadMaxAcceptedForecasts[betNextId] = maxAcceptedForecast; require(forecast>0 && forecast < maxAcceptedForecast,"Forecast should be grater than zero and less than Max accepted forecast(All options true)"); bets[betNextId].payoutRate = payoutRate; headToHeadForecasts[betNextId][msg.sender] = forecast; } playerBetTotalBets[msg.sender][betNextId] = 1; betTotalBets[betNextId] = 1; betTotalAmount[betNextId] = wager; totalBets += 1; totalAmountOnBets += wager; if (houseData.housePercentage>0) { houseEdgeAmountForBet[betNextId] += mulByFraction(wager, houseData.housePercentage, 1000); } if (houseData.oraclePercentage>0) { oracleEdgeAmountForBet[betNextId] += mulByFraction(wager, houseData.oraclePercentage, 1000); } balance[msg.sender] -= wager; betForcastTotalAmount[betNextId][forecast] = wager; playerBetTotalAmount[msg.sender][betNextId] = wager; playerBetForecastWager[msg.sender][betNextId][forecast] = wager; totalPlayerBets[msg.sender] += 1; totalPlayerBetsAmount[msg.sender] += wager; lastBettingActivity = block.number; emit BetPlacedOrModified(betNextId, msg.sender, BetEvent.placeBet, wager, forecast, createdBy, bets[betNextId].closeDateTime); } /* * Call a Bet */ function callBet(uint betId, uint forecast, uint256 wager, string memory createdBy) public { require(wager>0,"Wager should be greater than zero"); require(balance[msg.sender]>=wager,"Not enough balance"); require(bets[betId].betType == BetType.headtohead || bets[betId].betType == BetType.poolbet,"Only poolbet and headtohead bets are implemented"); require(bets[betId].betType != BetType.headtohead || betTotalBets[betId] == 1,"Head to head bet has been already called"); require(wager>=bets[betId].minimumWager,"Wager is lower than the minimum accepted"); require(bets[betId].maximumWager==0 || wager<=bets[betId].maximumWager,"Wager is higher then the maximum accepted"); updateBetDataFromOracle(betId); require(!bets[betId].isCancelled,"Bet has been cancelled"); require(!bets[betId].isOutcomeSet,"Event has already an outcome"); require(bets[betId].closeDateTime >= now,"Close time has passed"); if (bets[betId].betType == BetType.headtohead) { require(bets[betId].createdBy != msg.sender,"Player has been opened the bet"); require(wager == mulByFraction( betTotalAmount[betId], bets[betId].payoutRate - 100, 100),"Wager should be equal to [Opened bet Wager * PayoutRate - 100]"); require(headToHeadForecasts[betId][bets[betId].createdBy] & forecast == 0,"Forecast overlaps opened bet forecast"); require(headToHeadForecasts[betId][bets[betId].createdBy] | forecast == headToHeadMaxAcceptedForecasts[betId],"Forecast should be opposite to the opened"); headToHeadForecasts[betId][msg.sender] = forecast; } else if (bets[betId].betType == BetType.poolbet) { require(playerBetForecastWager[msg.sender][betId][forecast] == 0,"Already placed a bet on this forecast, use increaseWager method instead"); } betTotalBets[betId] += 1; betTotalAmount[betId] += wager; totalAmountOnBets += wager; if (houseData.housePercentage>0) { houseEdgeAmountForBet[betId] += mulByFraction(wager, houseData.housePercentage, 1000); } if (houseData.oraclePercentage>0) { oracleEdgeAmountForBet[betId] += mulByFraction(wager, houseData.oraclePercentage, 1000); } balance[msg.sender] -= wager; playerBetTotalBets[msg.sender][betId] += 1; betForcastTotalAmount[betId][forecast] += wager; playerBetTotalAmount[msg.sender][betId] += wager; playerBetForecastWager[msg.sender][betId][forecast] = wager; totalPlayerBets[msg.sender] += 1; totalPlayerBetsAmount[msg.sender] += wager; lastBettingActivity = block.number; emit BetPlacedOrModified(betId, msg.sender, BetEvent.callBet, wager, forecast, createdBy, bets[betId].closeDateTime); } /* * Increase wager */ function increaseWager(uint betId, uint forecast, uint256 additionalWager, string memory createdBy) public { require(additionalWager>0,"Increase wager amount should be greater than zero"); require(balance[msg.sender]>=additionalWager,"Not enough balance"); require(bets[betId].betType == BetType.poolbet,"Only poolbet supports the increaseWager"); require(playerBetForecastWager[msg.sender][betId][forecast] > 0,"Haven't placed any bet for this forecast. Use callBet instead"); uint256 wager = playerBetForecastWager[msg.sender][betId][forecast] + additionalWager; require(bets[betId].maximumWager==0 || wager<=bets[betId].maximumWager,"The updated wager is higher then the maximum accepted"); updateBetDataFromOracle(betId); require(!bets[betId].isCancelled,"Bet has been cancelled"); require(!bets[betId].isOutcomeSet,"Event has already an outcome"); require(bets[betId].closeDateTime >= now,"Close time has passed"); betTotalAmount[betId] += additionalWager; totalAmountOnBets += additionalWager; if (houseData.housePercentage>0) { houseEdgeAmountForBet[betId] += mulByFraction(additionalWager, houseData.housePercentage, 1000); } if (houseData.oraclePercentage>0) { oracleEdgeAmountForBet[betId] += mulByFraction(additionalWager, houseData.oraclePercentage, 1000); } balance[msg.sender] -= additionalWager; betForcastTotalAmount[betId][forecast] += additionalWager; playerBetTotalAmount[msg.sender][betId] += additionalWager; playerBetForecastWager[msg.sender][betId][forecast] += additionalWager; totalPlayerBetsAmount[msg.sender] += additionalWager; lastBettingActivity = block.number; emit BetPlacedOrModified(betId, msg.sender, BetEvent.increaseWager, additionalWager, forecast, createdBy, bets[betId].closeDateTime); } /* * Remove a Bet */ function removeBet(uint betId, string memory createdBy) public { require(bets[betId].createdBy == msg.sender,"Caller and player created don't match"); require(playerBetTotalBets[msg.sender][betId] > 0, "Player should has placed at least one bet"); require(betTotalBets[betId] == playerBetTotalBets[msg.sender][betId],"The bet has been called by other player"); require(bets[betId].betType == BetType.headtohead || bets[betId].betType == BetType.poolbet,"Only poolbet and headtohead bets are implemented"); updateBetDataFromOracle(betId); bets[betId].isCancelled = true; uint256 wager = betTotalAmount[betId]; betTotalBets[betId] = 0; betTotalAmount[betId] = 0; totalBets -= playerBetTotalBets[msg.sender][betId]; totalAmountOnBets -= wager; houseEdgeAmountForBet[betId] = 0; oracleEdgeAmountForBet[betId] = 0; balance[msg.sender] += wager; playerBetTotalAmount[msg.sender][betId] = 0; totalPlayerBets[msg.sender] -= playerBetTotalBets[msg.sender][betId]; totalPlayerBetsAmount[msg.sender] -= wager; playerBetTotalBets[msg.sender][betId] = 0; lastBettingActivity = block.number; emit BetPlacedOrModified(betId, msg.sender, BetEvent.removeBet, wager, 0, createdBy, bets[betId].closeDateTime); } /* * Refute a Bet */ function refuteBet(uint betId, string memory createdBy) public { require(playerBetTotalAmount[msg.sender][betId]>0,"Caller hasn't placed any bet"); require(!playerBetRefuted[msg.sender][betId],"Already refuted"); require(bets[betId].betType == BetType.headtohead || bets[betId].betType == BetType.poolbet,"Only poolbet and headtohead bets are implemented"); updateBetDataFromOracle(betId); require(bets[betId].isOutcomeSet, "Refute isn't allowed when no outcome has been set"); require(bets[betId].freezeDateTime > now, "Refute isn't allowed when Event freeze has passed"); playerBetRefuted[msg.sender][betId] = true; betRefutedAmount[betId] += playerBetTotalAmount[msg.sender][betId]; if (betRefutedAmount[betId] >= betTotalAmount[betId]) { bets[betId].isCancelled = true; } lastBettingActivity = block.number; emit BetPlacedOrModified(betId, msg.sender, BetEvent.refuteBet, 0, 0, createdBy, bets[betId].closeDateTime); } /* * Settle a Bet */ function settleBet(uint betId, string memory createdBy) public { require(playerBetTotalAmount[msg.sender][betId]>0, "Caller hasn't placed any bet"); require(!playerBetSettled[msg.sender][betId],"Already settled"); require(bets[betId].betType == BetType.headtohead || bets[betId].betType == BetType.poolbet,"Only poolbet and headtohead bets are implemented"); updateBetDataFromOracle(betId); require(bets[betId].isCancelled || bets[betId].isOutcomeSet,"Bet should be cancelled or has an outcome"); require(bets[betId].freezeDateTime <= now,"Bet payments are freezed"); BetEvent betEvent; if (bets[betId].isCancelled) { betEvent = BetEvent.settleCancelledBet; houseEdgeAmountForBet[betId] = 0; oracleEdgeAmountForBet[betId] = 0; playerOutputFromBet[msg.sender][betId] = playerBetTotalAmount[msg.sender][betId]; } else { if (!housePaid[betId] && houseEdgeAmountForBet[betId] > 0) { for (uint i = 0; i<owners.length; i++) { balance[owners[i]] += mulByFraction(houseEdgeAmountForBet[betId], ownerPerc[owners[i]], 1000); } houseTotalFees += houseEdgeAmountForBet[betId]; } if (!housePaid[betId] && oracleEdgeAmountForBet[betId] > 0) { address oracleOwner = HouseContract(bets[betId].oracleAddress).owner(); balance[oracleOwner] += oracleEdgeAmountForBet[betId]; oracleTotalFees[bets[betId].oracleAddress] += oracleEdgeAmountForBet[betId]; } housePaid[betId] = true; uint256 totalBetAmountAfterFees = betTotalAmount[betId] - houseEdgeAmountForBet[betId] - oracleEdgeAmountForBet[betId]; if (bets[betId].betType == BetType.poolbet) { if (betForcastTotalAmount[betId][bets[betId].outcome]>0) { playerOutputFromBet[msg.sender][betId] = mulByFraction(totalBetAmountAfterFees, playerBetForecastWager[msg.sender][betId][bets[betId].outcome], betForcastTotalAmount[betId][bets[betId].outcome]); } else { playerOutputFromBet[msg.sender][betId] = playerBetTotalAmount[msg.sender][betId] - mulByFraction(playerBetTotalAmount[msg.sender][betId], houseData.housePercentage, 1000) - mulByFraction(playerBetTotalAmount[msg.sender][betId], houseData.oraclePercentage, 1000); } } else if (bets[betId].betType == BetType.headtohead) { if (headToHeadForecasts[betId][msg.sender] & (2 ** bets[betId].outcome) > 0) { playerOutputFromBet[msg.sender][betId] = totalBetAmountAfterFees; } else { playerOutputFromBet[msg.sender][betId] = 0; } } require(playerOutputFromBet[msg.sender][betId] > 0,"Settled amount should be grater than zero"); betEvent = BetEvent.settleWinnedBet; } playerBetSettled[msg.sender][betId] = true; balance[msg.sender] += playerOutputFromBet[msg.sender][betId]; lastBettingActivity = block.number; emit BetPlacedOrModified(betId, msg.sender, betEvent, playerOutputFromBet[msg.sender][betId],0, createdBy, bets[betId].closeDateTime); } function() external payable { balance[msg.sender] = add(balance[msg.sender],msg.value); emit transfer(msg.sender,msg.value,true); } /** * Checks if a player has betting activity on House */ function isPlayer(address playerAddress) public view returns(bool) { return (totalPlayerBets[playerAddress] > 0); } /** * Update House short message */ function updateShortMessage(string memory shortMessage) onlyOwner public { houseData.shortMessage = shortMessage; emit HousePropertiesUpdated(); } /** * Starts betting */ function startNewBets(string memory shortMessage) onlyOwner public { houseData.shortMessage = shortMessage; houseData.newBetsPaused = false; emit HousePropertiesUpdated(); } /** * Pauses betting */ function stopNewBets(string memory shortMessage) onlyOwner public { houseData.shortMessage = shortMessage; houseData.newBetsPaused = true; emit HousePropertiesUpdated(); } /** * Link House to a new version */ function linkToNewHouse(address newHouseAddress) onlyOwner public { require(newHouseAddress!=address(this),"New address is current address"); require(HouseContract(newHouseAddress).isHouse(),"New address should be a House smart contract"); _newHouseAddress = newHouseAddress; houseData.newBetsPaused = true; emit HousePropertiesUpdated(); } /** * UnLink House from a newer version */ function unLinkNewHouse() onlyOwner public { _newHouseAddress = address(0); houseData.newBetsPaused = false; emit HousePropertiesUpdated(); } /** * Cancels a Bet */ function cancelBet(uint betId) onlyOwner public { require(houseData.managed, "Cancel available on managed Houses"); updateBetDataFromOracle(betId); require(bets[betId].freezeDateTime > now,"Freeze time passed"); bets[betId].isCancelled = true; emit BetPlacedOrModified(betId, msg.sender, BetEvent.cancelledByHouse, 0, 0, "", bets[betId].closeDateTime); } /** * Settle fees of Oracle and House for a bet */ function settleBetFees(uint betId) onlyOwner public { require(bets[betId].isCancelled || bets[betId].isOutcomeSet,"Bet should be cancelled or has an outcome"); require(bets[betId].freezeDateTime <= now,"Bet payments are freezed"); if (!housePaid[betId] && houseEdgeAmountForBet[betId] > 0) { for (uint i = 0; i<owners.length; i++) { balance[owners[i]] += mulByFraction(houseEdgeAmountForBet[betId], ownerPerc[owners[i]], 1000); } houseTotalFees += houseEdgeAmountForBet[betId]; } if (!housePaid[betId] && oracleEdgeAmountForBet[betId] > 0) { address oracleOwner = HouseContract(bets[betId].oracleAddress).owner(); balance[oracleOwner] += oracleEdgeAmountForBet[betId]; oracleTotalFees[bets[betId].oracleAddress] += oracleEdgeAmountForBet[betId]; } housePaid[betId] = true; } /** * Withdraw the requested amount to the sender address */ function withdraw(uint256 amount) public { require(address(this).balance>=amount,"Insufficient House balance. Shouldn't have happened"); require(balance[msg.sender]>=amount,"Insufficient balance"); balance[msg.sender] = sub(balance[msg.sender],amount); msg.sender.transfer(amount); emit transfer(msg.sender,amount,false); } /** * Withdraw the requested amount to an address */ function withdrawToAddress(address payable destinationAddress,uint256 amount) public { require(address(this).balance>=amount); require(balance[msg.sender]>=amount,"Insufficient balance"); balance[msg.sender] = sub(balance[msg.sender],amount); destinationAddress.transfer(amount); emit transfer(msg.sender,amount,false); } }
Notifies clients that a new house is launched
event HouseCreated();
1,048,625
[ 1, 1248, 5032, 7712, 716, 279, 394, 23867, 353, 28786, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 871, 670, 3793, 6119, 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 ]
// SPDX-License-Identifier: MIT /* * MIT License * =========== * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE */ pragma solidity 0.7.6; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../libraries/MathLib.sol"; import "../interfaces/IPendleRouter.sol"; import "../interfaces/IPendleData.sol"; import "../interfaces/IPendleForge.sol"; import "../interfaces/IPendleMarketFactory.sol"; import "../interfaces/IPendleMarket.sol"; import "../periphery/Permissions.sol"; import "../periphery/Withdrawable.sol"; import "../periphery/PendleNonReentrant.sol"; contract PendleRouter is IPendleRouter, Permissions, Withdrawable, PendleNonReentrant { using SafeERC20 for IERC20; using SafeMath for uint256; IWETH public immutable override weth; IPendleData public override data; address private constant ETH_ADDRESS = address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE); address private constant DUMMY_ERC20 = address(0x123); constructor(address _governance, IWETH _weth) Permissions(_governance) { weth = _weth; _reentrancyStatus = _NOT_ENTERED; } /** * @dev Accepts ETH via fallback from the WETH contract. **/ receive() external payable {} function initialize(IPendleData _data) external { require(msg.sender == initializer, "FORBIDDEN"); require(address(_data) != address(0), "ZERO_ADDRESS"); initializer = address(0); data = _data; } /*********** * FORGE * ***********/ /** * @notice forges are identified by forgeIds **/ function addForge(bytes32 _forgeId, address _forgeAddress) external override initialized onlyGovernance pendleNonReentrant { require(_forgeId != bytes32(0), "ZERO_BYTES"); require(_forgeAddress != address(0), "ZERO_ADDRESS"); require(_forgeId == IPendleForge(_forgeAddress).forgeId(), "INVALID_ID"); require(data.getForgeAddress(_forgeId) == address(0), "EXISTED_ID"); data.addForge(_forgeId, _forgeAddress); emit NewForge(_forgeId, _forgeAddress); } /** * @notice Create a new pair of OT + XYT tokens to represent the * principal and interest for an underlying asset, until an expiry **/ function newYieldContracts( bytes32 _forgeId, address _underlyingAsset, uint256 _expiry ) external override pendleNonReentrant returns (address ot, address xyt) { require(_underlyingAsset != address(0), "ZERO_ADDRESS"); require(_expiry > block.timestamp, "INVALID_EXPIRY"); IPendleForge forge = IPendleForge(data.getForgeAddress(_forgeId)); require(address(forge) != address(0), "FORGE_NOT_EXISTS"); ot = address(data.otTokens(_forgeId, _underlyingAsset, _expiry)); xyt = address(data.xytTokens(_forgeId, _underlyingAsset, _expiry)); require(ot == address(0) && xyt == address(0), "DUPLICATE_YIELD_CONTRACT"); (ot, xyt) = forge.newYieldContracts(_underlyingAsset, _expiry); } /** * @notice After an expiry, redeem OT tokens to get back the underlyingYieldToken * and also any interests * @notice This function acts as a proxy to the actual function * @dev The interest from "the last global action before expiry" until the expiry * is given to the OT holders. This is to simplify accounting. An assumption * is that the last global action before expiry will be close to the expiry * @dev all validity checks are in the internal function **/ function redeemAfterExpiry( bytes32 _forgeId, address _underlyingAsset, uint256 _expiry, address _to ) external override pendleNonReentrant returns (uint256 redeemedAmount) { redeemedAmount = _redeemAfterExpiryInternal(_forgeId, _underlyingAsset, _expiry, _to); } /** * @notice an XYT holder can redeem his acrued interests anytime * @notice This function acts as a proxy to the actual function * @dev all validity checks are in the internal function **/ function redeemDueInterests( bytes32 _forgeId, address _underlyingAsset, uint256 _expiry ) external override pendleNonReentrant returns (uint256 interests) { interests = _redeemDueInterestsInternal(_forgeId, _underlyingAsset, _expiry); } /** * @notice redeem interests for multiple XYTs * @dev all validity checks are in the internal function **/ function redeemDueInterestsMultiple( bytes32[] calldata _forgeIds, address[] calldata _underlyingAssets, uint256[] calldata _expiries ) external override pendleNonReentrant returns (uint256[] memory interests) { require( _forgeIds.length == _underlyingAssets.length && _forgeIds.length == _expiries.length, "INVALID_ARRAYS" ); interests = new uint256[](_forgeIds.length); for (uint256 i = 0; i < _forgeIds.length; i++) { interests[i] = _redeemDueInterestsInternal( _forgeIds[i], _underlyingAssets[i], _expiries[i] ); } } /** * @notice Before the expiry, a user can redeem the same amount of OT+XYT to get back * the underlying yield token * @dev no check on _amountToRedeem **/ function redeemUnderlying( bytes32 _forgeId, address _underlyingAsset, uint256 _expiry, uint256 _amountToRedeem, address _to ) external override pendleNonReentrant returns (uint256 redeemedAmount) { require(data.isValidXYT(_forgeId, _underlyingAsset, _expiry), "INVALID_XYT"); require(block.timestamp < _expiry, "YIELD_CONTRACT_EXPIRED"); require(_to != address(0), "ZERO_ADDRESS"); IPendleForge forge = IPendleForge(data.getForgeAddress(_forgeId)); redeemedAmount = forge.redeemUnderlying( msg.sender, _underlyingAsset, _expiry, _amountToRedeem, _to ); } /** * @notice redeemAfterExpiry and tokenizeYield to a different expiry * @dev checks for all params except _newExpiry are in internal functions **/ function renewYield( bytes32 _forgeId, uint256 _oldExpiry, address _underlyingAsset, uint256 _newExpiry, uint256 _amountToTokenize, address _yieldTo ) external override pendleNonReentrant returns ( uint256 redeemedAmount, address ot, address xyt, uint256 amountTokenMinted ) { require(_newExpiry > _oldExpiry, "INVALID_NEW_EXPIRY"); redeemedAmount = _redeemAfterExpiryInternal( _forgeId, _underlyingAsset, _oldExpiry, msg.sender ); (ot, xyt, amountTokenMinted) = _tokenizeYieldInternal( _forgeId, _underlyingAsset, _newExpiry, _amountToTokenize, _yieldTo ); } /** * @notice tokenize a yield bearing token to get OT+XYT * @notice This function acts as a proxy to the actual function * @dev each forge is for a yield protocol (for example: Aave, Compound) * @dev all checks are in the internal function **/ function tokenizeYield( bytes32 _forgeId, address _underlyingAsset, uint256 _expiry, uint256 _amountToTokenize, address _to ) external override pendleNonReentrant returns ( address ot, address xyt, uint256 amountTokenMinted ) { (ot, xyt, amountTokenMinted) = _tokenizeYieldInternal( _forgeId, _underlyingAsset, _expiry, _amountToTokenize, _to ); } /*********** * MARKET * ***********/ /** * @notice market factories are identified by marketFactoryId * @dev A market factory can work with XYTs from one or more Forges, * to be determined by data.validForgeFactoryPair mapping **/ function addMarketFactory(bytes32 _marketFactoryId, address _marketFactoryAddress) external override initialized onlyGovernance pendleNonReentrant { require(_marketFactoryId != bytes32(0), "ZERO_BYTES"); require(_marketFactoryAddress != address(0), "ZERO_ADDRESS"); require( _marketFactoryId == IPendleMarketFactory(_marketFactoryAddress).marketFactoryId(), "INVALID_FACTORY_ID" ); require(data.getMarketFactoryAddress(_marketFactoryId) == address(0), "EXISTED_ID"); data.addMarketFactory(_marketFactoryId, _marketFactoryAddress); emit NewMarketFactory(_marketFactoryId, _marketFactoryAddress); } /** * @notice add market liquidity by xyt and base tokens * @dev no checks on _maxInXyt, _maxInToken, _exactOutLp */ function addMarketLiquidityAll( bytes32 _marketFactoryId, address _xyt, address _token, uint256 _maxInXyt, uint256 _maxInToken, uint256 _exactOutLp ) external payable override pendleNonReentrant { address originalToken = _token; _token = _isETH(_token) ? address(weth) : _token; IPendleMarket market = IPendleMarket(data.getMarket(_marketFactoryId, _xyt, _token)); require(address(market) != address(0), "MARKET_NOT_FOUND"); PendingTransfer[3] memory transfers = market.addMarketLiquidityAll(_exactOutLp, _maxInXyt, _maxInToken); emit Join(msg.sender, transfers[0].amount, transfers[1].amount, address(market)); _settlePendingTransfers(transfers, _xyt, originalToken, address(market)); } /** * @notice add market liquidity by xyt and base tokens * @dev no checks on _maxInXyt, _maxInToken, _exactOutLp */ function addMarketLiquidityDual( bytes32 _marketFactoryId, address _xyt, address _token, uint256 _desiredXytAmount, uint256 _desiredTokenAmount, uint256 _xytMinAmount, uint256 _tokenMinAmount ) public payable override pendleNonReentrant returns ( uint256 amountXytUsed, uint256 amountTokenUsed, uint256 lpOut ) { require(_desiredXytAmount != 0, "ZERO_XYT_AMOUNT"); require(_desiredTokenAmount != 0, "ZERO_TOKEN_AMOUNT"); address originalToken = _token; _token = _isETH(_token) ? address(weth) : _token; IPendleMarket market = IPendleMarket(data.getMarket(_marketFactoryId, _xyt, _token)); require(address(market) != address(0), "MARKET_NOT_FOUND"); PendingTransfer[3] memory transfers; (transfers, lpOut) = market.addMarketLiquidityDual( _desiredXytAmount, _desiredTokenAmount, _xytMinAmount, _tokenMinAmount ); amountXytUsed = transfers[0].amount; amountTokenUsed = transfers[1].amount; emit Join(msg.sender, transfers[0].amount, transfers[1].amount, address(market)); _settlePendingTransfers(transfers, _xyt, originalToken, address(market)); } /** * @notice add market liquidity by xyt or base token * @dev no checks on _exactInAsset, _minOutLp */ function addMarketLiquiditySingle( bytes32 _marketFactoryId, address _xyt, address _token, bool _forXyt, uint256 _exactInAsset, uint256 _minOutLp ) external payable override pendleNonReentrant { address originalToken = _token; _token = _isETH(_token) ? address(weth) : _token; IPendleMarket market = IPendleMarket(data.getMarket(_marketFactoryId, _xyt, _token)); require(address(market) != address(0), "MARKET_NOT_FOUND"); address assetToTransferIn = _forXyt ? _xyt : originalToken; address assetForMarket = _forXyt ? _xyt : _token; PendingTransfer[3] memory transfers = market.addMarketLiquiditySingle(assetForMarket, _exactInAsset, _minOutLp); _settlePendingTransfers(transfers, assetToTransferIn, DUMMY_ERC20, address(market)); if (_forXyt) { emit Join(msg.sender, _exactInAsset, 0, address(market)); } else { emit Join(msg.sender, 0, _exactInAsset, address(market)); } } /** * @notice remove market liquidity by xyt and base tokens * @dev no checks on _exactInLp, _minOutXyt, _minOutToken */ function removeMarketLiquidityAll( bytes32 _marketFactoryId, address _xyt, address _token, uint256 _exactInLp, uint256 _minOutXyt, uint256 _minOutToken ) external override pendleNonReentrant returns (uint256 exactOutXyt, uint256 exactOutToken) { address originalToken = _token; _token = _isETH(_token) ? address(weth) : _token; IPendleMarket market = IPendleMarket(data.getMarket(_marketFactoryId, _xyt, _token)); require(address(market) != address(0), "MARKET_NOT_FOUND"); // since there is burning of LPs involved, we need to transfer in LP first // otherwise the market might not have enough LPs to burn PendingTransfer memory lpTransfer = PendingTransfer({amount: _exactInLp, isOut: false}); _settleTokenTransfer(address(market), lpTransfer, address(market)); PendingTransfer[3] memory transfers = market.removeMarketLiquidityAll(_exactInLp, _minOutXyt, _minOutToken); _settlePendingTransfers(transfers, _xyt, originalToken, address(market)); emit Exit(msg.sender, transfers[0].amount, transfers[1].amount, address(market)); return (transfers[0].amount, transfers[1].amount); } /** * @notice remove market liquidity by xyt or base tokens * @dev no checks on _exactInLp, _minOutAsset */ function removeMarketLiquiditySingle( bytes32 _marketFactoryId, address _xyt, address _token, bool _forXyt, uint256 _exactInLp, uint256 _minOutAsset ) external override pendleNonReentrant returns (uint256 exactOutXyt, uint256 exactOutToken) { address originalToken = _token; _token = _isETH(_token) ? address(weth) : _token; IPendleMarket market = IPendleMarket(data.getMarket(_marketFactoryId, _xyt, _token)); require(address(market) != address(0), "MARKET_NOT_FOUND"); /* _transferIn(address(market), _exactInLp); */ address assetForMarket = _forXyt ? _xyt : _token; // since there is burning of LPs involved, we need to transfer in LP first // otherwise the market might not have enough LPs to burn PendingTransfer memory lpTransfer = PendingTransfer({amount: _exactInLp, isOut: false}); _settleTokenTransfer(address(market), lpTransfer, address(market)); PendingTransfer[3] memory transfers = market.removeMarketLiquiditySingle(assetForMarket, _exactInLp, _minOutAsset); address assetToTransferOut = _forXyt ? _xyt : originalToken; _settleTokenTransfer(assetToTransferOut, transfers[0], address(market)); if (_forXyt) { emit Exit(msg.sender, transfers[0].amount, 0, address(market)); return (transfers[0].amount, 0); } else { emit Exit(msg.sender, 0, transfers[0].amount, address(market)); return (0, transfers[0].amount); } } /** * @notice create a new market for a pair of xyt & token */ function createMarket( bytes32 _marketFactoryId, address _xyt, address _token ) external override pendleNonReentrant returns (address market) { require(_xyt != address(0), "ZERO_ADDRESS"); require(_token != address(0), "ZERO_ADDRESS"); require(data.isXyt(_xyt), "INVALID_XYT"); require(!data.isXyt(_token), "XYT_QUOTE_PAIR_FORBIDDEN"); require(data.getMarket(_marketFactoryId, _xyt, _token) == address(0), "EXISTED_MARKET"); IPendleMarketFactory factory = IPendleMarketFactory(data.getMarketFactoryAddress(_marketFactoryId)); require(address(factory) != address(0), "ZERO_ADDRESS"); bytes32 forgeId = IPendleForge(IPendleYieldToken(_xyt).forge()).forgeId(); require(data.validForgeFactoryPair(forgeId, _marketFactoryId), "INVALID_FORGE_FACTORY"); market = factory.createMarket(_xyt, _token); IERC20(_xyt).safeApprove(market, type(uint256).max); IERC20(_token).safeApprove(market, type(uint256).max); IERC20(market).safeApprove(market, type(uint256).max); } /** * @notice bootstrap a market (aka the first one to add liquidity) * @dev Users can either set _token as ETH or WETH to trade with XYT-WETH markets * If they put in ETH, they must send ETH along and _token will be auto wrapped to WETH * If they put in WETH, the function will run the same as other tokens */ function bootstrapMarket( bytes32 _marketFactoryId, address _xyt, address _token, uint256 _initialXytLiquidity, uint256 _initialTokenLiquidity ) external payable override pendleNonReentrant { require(_initialXytLiquidity > 0, "INVALID_XYT_AMOUNT"); require(_initialTokenLiquidity > 0, "INVALID_TOKEN_AMOUNT"); address originalToken = _token; _token = _isETH(_token) ? address(weth) : _token; IPendleMarket market = IPendleMarket(data.getMarket(_marketFactoryId, _xyt, _token)); require(address(market) != address(0), "MARKET_NOT_FOUND"); PendingTransfer[3] memory transfers = market.bootstrap(_initialXytLiquidity, _initialTokenLiquidity); emit Join(msg.sender, _initialXytLiquidity, _initialTokenLiquidity, address(market)); _settlePendingTransfers(transfers, _xyt, originalToken, address(market)); } /** * @notice trade by swap exact amount of token into market * @dev no checks on _inTotalAmount, _minOutTotalAmount, _maxPrice */ function swapExactIn( address _tokenIn, address _tokenOut, uint256 _inTotalAmount, uint256 _minOutTotalAmount, uint256 _maxPrice, bytes32 _marketFactoryId ) external payable override pendleNonReentrant returns (uint256 outSwapAmount) { address originalTokenIn = _tokenIn; address originalTokenOut = _tokenOut; _tokenIn = _isETH(_tokenIn) ? address(weth) : _tokenIn; _tokenOut = _isETH(_tokenOut) ? address(weth) : _tokenOut; IPendleMarket market = IPendleMarket(data.getMarketFromKey(_tokenIn, _tokenOut, _marketFactoryId)); require(address(market) != address(0), "MARKET_NOT_FOUND"); PendingTransfer[3] memory transfers; (outSwapAmount, , transfers) = market.swapExactIn( _tokenIn, _inTotalAmount, _tokenOut, _minOutTotalAmount, _maxPrice ); _settlePendingTransfers(transfers, originalTokenIn, originalTokenOut, address(market)); emit SwapEvent( msg.sender, _tokenIn, _tokenOut, _inTotalAmount, outSwapAmount, address(market) ); } /** * @notice trade by swap exact amount of token out of market * @dev no checks on _outTotalAmount, _maxInTotalAmount, _maxPrice */ function swapExactOut( address _tokenIn, address _tokenOut, uint256 _outTotalAmount, uint256 _maxInTotalAmount, uint256 _maxPrice, bytes32 _marketFactoryId ) external payable override pendleNonReentrant returns (uint256 inSwapAmount) { address originalTokenIn = _tokenIn; address originalTokenOut = _tokenOut; _tokenIn = _isETH(_tokenIn) ? address(weth) : _tokenIn; _tokenOut = _isETH(_tokenOut) ? address(weth) : _tokenOut; IPendleMarket market = IPendleMarket(data.getMarketFromKey(_tokenIn, _tokenOut, _marketFactoryId)); require(address(market) != address(0), "MARKET_NOT_FOUND"); PendingTransfer[3] memory transfers; (inSwapAmount, , transfers) = market.swapExactOut( _tokenIn, _maxInTotalAmount, _tokenOut, _outTotalAmount, _maxPrice ); _settlePendingTransfers(transfers, originalTokenIn, originalTokenOut, address(market)); emit SwapEvent( msg.sender, _tokenIn, _tokenOut, inSwapAmount, _outTotalAmount, address(market) ); } /** * @dev Needed for multi-path off-chain routing * @dev _swapPath = [swapRoute1, swapRoute2] where swapRoute1 = [Swap1, swap2..] is a series of * swaps to convert from _tokenIn to _tokenOut * @dev _tokenIn and _tokenOut can be ETH_ADDRESS, which means we will use ETH to trade * @dev however, any tokens in between the swap route must be a real ERC20 address (so it should be WETH if ETH is involved) */ function swapPathExactIn( Swap[][] memory _swapPath, address _tokenIn, address _tokenOut, uint256 _inTotalAmount, uint256 _minOutTotalAmount ) external payable override pendleNonReentrant returns (uint256 outTotalAmount) { uint256 sumInAmount; for (uint256 i = 0; i < _swapPath.length; i++) { uint256 swapRouteLength = _swapPath[i].length; require( _swapPath[i][0].tokenIn == _tokenIn && _swapPath[i][swapRouteLength - 1].tokenOut == _tokenOut, "INVALID_PATH" ); sumInAmount = sumInAmount.add(_swapPath[i][0].swapAmount); uint256 tokenAmountOut; for (uint256 j = 0; j < _swapPath[i].length; j++) { Swap memory swap = _swapPath[i][j]; swap.tokenIn = _getMarketToken(swap.tokenIn); // make it weth if its eth swap.tokenOut = _getMarketToken(swap.tokenOut); // make it weth if its eth if (j >= 1) { swap.swapAmount = tokenAmountOut; // if its not the first swap, then we need to send the output of the last swap // to the current market as input for the current swap IERC20(swap.tokenIn).safeTransferFrom( _swapPath[i][j - 1].market, swap.market, swap.swapAmount ); } IPendleMarket market = IPendleMarket(swap.market); _checkMarketTokens(swap.tokenIn, swap.tokenOut, market); (tokenAmountOut, , ) = market.swapExactIn( swap.tokenIn, swap.swapAmount, swap.tokenOut, swap.limitReturnAmount, swap.maxPrice ); } // sends in the exactAmount into the market of the first swap _settleTokenTransfer( _tokenIn, PendingTransfer({amount: _swapPath[i][0].swapAmount, isOut: false}), _swapPath[i][0].market ); // gets the tokenOut from the market of the last swap _settleTokenTransfer( _tokenOut, PendingTransfer({amount: tokenAmountOut, isOut: true}), _swapPath[i][swapRouteLength - 1].market ); outTotalAmount = tokenAmountOut.add(outTotalAmount); } require(sumInAmount == _inTotalAmount, "INVALID_AMOUNTS"); require(outTotalAmount >= _minOutTotalAmount, "LIMIT_OUT_ERROR"); } /** * @dev Needed for multi-path off-chain routing * @dev Similarly to swapPathExactIn, but we do the swaps in reverse */ function swapPathExactOut( Swap[][] memory _swapPath, address _tokenIn, address _tokenOut, uint256 _maxInTotalAmount ) external payable override pendleNonReentrant returns (uint256 inTotalAmount) { for (uint256 i = 0; i < _swapPath.length; i++) { uint256 swapRouteLength = _swapPath[i].length; require( _swapPath[i][0].tokenIn == _tokenIn && _swapPath[i][swapRouteLength - 1].tokenOut == _tokenOut, "INVALID_PATH" ); uint256 tokenAmountIn; for (uint256 j = _swapPath[i].length - 1; j >= 0; j--) { Swap memory swap = _swapPath[i][j]; swap.tokenIn = _getMarketToken(swap.tokenIn); // make it weth if its eth swap.tokenOut = _getMarketToken(swap.tokenOut); // make it weth if its eth if (j < _swapPath[i].length - 1) { swap.swapAmount = tokenAmountIn; IERC20(swap.tokenOut).safeTransferFrom( swap.market, _swapPath[i][j + 1].market, swap.swapAmount ); } IPendleMarket market = IPendleMarket(swap.market); _checkMarketTokens(swap.tokenIn, swap.tokenOut, market); (tokenAmountIn, , ) = market.swapExactOut( swap.tokenIn, swap.limitReturnAmount, swap.tokenOut, swap.swapAmount, swap.maxPrice ); if (j == 0) break; } _settleTokenTransfer( _tokenIn, PendingTransfer({amount: tokenAmountIn, isOut: false}), _swapPath[i][0].market ); // send out _tokenOut last _settleTokenTransfer( _tokenOut, PendingTransfer({ amount: _swapPath[i][swapRouteLength - 1].swapAmount, isOut: true }), _swapPath[i][swapRouteLength - 1].market ); inTotalAmount = tokenAmountIn.add(inTotalAmount); } require(inTotalAmount <= _maxInTotalAmount, "LIMIT_IN_ERROR"); } /** * @notice Lp holders are entitled to receive the interests from the underlying XYTs * they can call this function to claim the acrued interests */ function claimLpInterests(address[] calldata markets) external override pendleNonReentrant returns (uint256[] memory interests) { interests = new uint256[](markets.length); for (uint256 i = 0; i < markets.length; i++) { require(data.isMarket(markets[i]), "INVALID_MARKET"); interests[i] = IPendleMarket(markets[i]).claimLpInterests(msg.sender); } } function _getData() internal view override returns (IPendleData) { return data; } function _isETH(address token) internal pure returns (bool) { return (token == ETH_ADDRESS); } function _redeemDueInterestsInternal( bytes32 _forgeId, address _underlyingAsset, uint256 _expiry ) internal returns (uint256 interests) { require(data.isValidXYT(_forgeId, _underlyingAsset, _expiry), "INVALID_XYT"); IPendleForge forge = IPendleForge(data.getForgeAddress(_forgeId)); interests = forge.redeemDueInterests(msg.sender, _underlyingAsset, _expiry); } function _redeemAfterExpiryInternal( bytes32 _forgeId, address _underlyingAsset, uint256 _expiry, address _to ) internal returns (uint256 redeemedAmount) { require(data.isValidXYT(_forgeId, _underlyingAsset, _expiry), "INVALID_XYT"); require(_to != address(0), "ZERO_ADDRESS"); require(_expiry < block.timestamp, "MUST_BE_AFTER_EXPIRY"); IPendleForge forge = IPendleForge(data.getForgeAddress(_forgeId)); redeemedAmount = forge.redeemAfterExpiry(msg.sender, _underlyingAsset, _expiry, _to); } /** * @dev no check on _amountToTokenize */ function _tokenizeYieldInternal( bytes32 _forgeId, address _underlyingAsset, uint256 _expiry, uint256 _amountToTokenize, address _to ) internal returns ( address ot, address xyt, uint256 amountTokenMinted ) { require(data.isValidXYT(_forgeId, _underlyingAsset, _expiry), "INVALID_XYT"); require(_to != address(0), "ZERO_ADDRESS"); IPendleForge forge = IPendleForge(data.getForgeAddress(_forgeId)); IERC20 underlyingToken = IERC20(forge.getYieldBearingToken(_underlyingAsset)); underlyingToken.transferFrom(msg.sender, address(forge), _amountToTokenize); // Due to possible precision error, we will only mint the amount of OT & XYT equals // to the amount of tokens that the contract receives (ot, xyt, amountTokenMinted) = forge.tokenizeYield( _underlyingAsset, _expiry, _amountToTokenize, _to ); } /** * @notice This function takes in the standard array PendingTransfer[3] that represents * any pending transfers of tokens to be done between a market and msg.sender * @dev transfers[0] and transfers[1] always represent the tokens that are traded * while transfers[2] always represent LP transfers * The convention is that: * - if its a function with xyt and baseToken, transfers[0] is always xyt * - if its a function with tokenIn and tokenOut, transfers[0] is always tokenOut * */ function _settlePendingTransfers( PendingTransfer[3] memory transfers, address firstToken, address secondToken, address market ) internal { _settleTokenTransfer(firstToken, transfers[0], market); _settleTokenTransfer(secondToken, transfers[1], market); _settleTokenTransfer(market, transfers[2], market); } /** * @notice This function settles a PendingTransfer, where the token could be ETH_ADDRESS * a PendingTransfer is always between a market and msg.sender */ function _settleTokenTransfer( address token, PendingTransfer memory transfer, address market ) internal { if (transfer.amount == 0) { return; } if (transfer.isOut) { if (_isETH(token)) { weth.transferFrom(market, address(this), transfer.amount); weth.withdraw(transfer.amount); (bool success, ) = msg.sender.call{value: transfer.amount}(""); require(success, "TRANSFER_FAILED"); } else { IERC20(token).safeTransferFrom(market, msg.sender, transfer.amount); } } else { if (_isETH(token)) { require(msg.value == transfer.amount, "ETH_SENT_MISMATCH"); weth.deposit{value: msg.value}(); weth.transfer(market, transfer.amount); } else { IERC20(token).safeTransferFrom(msg.sender, market, transfer.amount); } } } function _checkMarketTokens( address token1, address token2, IPendleMarket market ) internal view { require(data.isMarket(address(market)), "INVALID_MARKET"); require( data.getMarketFromKey(token1, token2, market.factoryId()) == address(market), "INVALID_MARKET" ); } /** * @notice This function turns ETH_ADDRESS into WETH address if applicable * it is called "marketToken" because its the token address used in the markets */ function _getMarketToken(address token) internal view returns (address) { if (_isETH(token)) return address(weth); return token; } }
* @notice forges are identified by forgeIds/
function addForge(bytes32 _forgeId, address _forgeAddress) external override initialized onlyGovernance pendleNonReentrant { require(_forgeId != bytes32(0), "ZERO_BYTES"); require(_forgeAddress != address(0), "ZERO_ADDRESS"); require(_forgeId == IPendleForge(_forgeAddress).forgeId(), "INVALID_ID"); require(data.getForgeAddress(_forgeId) == address(0), "EXISTED_ID"); data.addForge(_forgeId, _forgeAddress); emit NewForge(_forgeId, _forgeAddress); }
12,866,224
[ 1, 1884, 2852, 854, 9283, 635, 21388, 2673, 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, 527, 1290, 908, 12, 3890, 1578, 389, 1884, 908, 548, 16, 1758, 389, 1884, 908, 1887, 13, 203, 3639, 3903, 203, 3639, 3849, 203, 3639, 6454, 203, 3639, 1338, 43, 1643, 82, 1359, 203, 3639, 31472, 298, 3989, 426, 8230, 970, 203, 565, 288, 203, 3639, 2583, 24899, 1884, 908, 548, 480, 1731, 1578, 12, 20, 3631, 315, 24968, 67, 13718, 8863, 203, 3639, 2583, 24899, 1884, 908, 1887, 480, 1758, 12, 20, 3631, 315, 24968, 67, 15140, 8863, 203, 3639, 2583, 24899, 1884, 908, 548, 422, 2971, 409, 298, 1290, 908, 24899, 1884, 908, 1887, 2934, 1884, 908, 548, 9334, 315, 9347, 67, 734, 8863, 203, 3639, 2583, 12, 892, 18, 588, 1290, 908, 1887, 24899, 1884, 908, 548, 13, 422, 1758, 12, 20, 3631, 315, 11838, 2056, 67, 734, 8863, 203, 203, 3639, 501, 18, 1289, 1290, 908, 24899, 1884, 908, 548, 16, 389, 1884, 908, 1887, 1769, 203, 203, 3639, 3626, 1166, 1290, 908, 24899, 1884, 908, 548, 16, 389, 1884, 908, 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 ]
pragma solidity 0.4.24; import "deps/openzeppelin-eth/2.0.2/contracts/math/SafeMath.sol"; import "deps/openzeppelin-eth/2.0.2/contracts/ownership/Ownable.sol"; import "deps/openzeppelin-eth/2.0.2/contracts/token/ERC20/ERC20Detailed.sol"; import "./lib/SafeMathInt.sol"; /** * @title uFragments ERC20 token * @dev This is part of an implementation of the uFragments Ideal Money protocol. * uFragments is a normal ERC20 token, but its supply can be adjusted by splitting and * combining tokens proportionally across all wallets. * * uFragment balances are internally represented with a hidden denomination, 'shares'. * We support splitting the currency in expansion and combining the currency on contraction by * changing the exchange rate between the hidden 'shares' and the public 'fragments'. */ contract UFragments is ERC20Detailed, Ownable { // PLEASE READ BEFORE CHANGING ANY ACCOUNTING OR MATH // Anytime there is division, there is a risk of numerical instability from rounding errors. In // order to minimize this risk, we adhere to the following guidelines: // 1) The conversion rate adopted is the number of shares that equals 1 fragment. // The inverse rate must not be used--TOTAL_SHARES is always the numerator and _totalSupply is // always the denominator. (i.e. If you want to convert shares to fragments instead of // multiplying by the inverse rate, you should divide by the normal rate) // 2) Share balances converted into Fragments are always rounded down (truncated). // // We make the following guarantees: // - If address 'A' transfers x Fragments to address 'B'. A's resulting external balance will // be decreased by precisely x Fragments, and B's external balance will be precisely // increased by x Fragments. // // We do not guarantee that the sum of all balances equals the result of calling totalSupply(). // This is because, for any conversion function 'f()' that has non-zero rounding error, // f(x0) + f(x1) + ... + f(xn) is not always equal to f(x0 + x1 + ... xn). using SafeMath for uint256; using SafeMathInt for int256; event LogRebase(uint256 indexed epoch, uint256 totalSupply); event LogMonetaryPolicyUpdated(address monetaryPolicy); // Used for authentication address public monetaryPolicy; uint256 public rebaseStartTime; modifier onlyMonetaryPolicy() { require(msg.sender == monetaryPolicy); _; } bool private rebasePausedDeprecated; bool private tokenPausedDeprecated; modifier validRecipient(address to) { require(to != address(0x0)); require(to != address(this)); _; } modifier onlyAfterRebaseStart() { require(now >= rebaseStartTime); _; } uint256 private constant DECIMALS = 9; uint256 private constant SCALED_SHARES_EXTRA_DECIMALS = 9; uint256 private constant MAX_UINT256 = ~uint256(0); uint256 private constant MAX_UINT128 = ~uint128(0); uint256 private constant MAX_FRAGMENTS_SUPPLY = 4000 * 10**DECIMALS; // TOTAL_SHARES is a multiple of MAX_FRAGMENTS_SUPPLY so that _sharesPerFragment is an integer. // Use the highest value that fits in a uint128 for sufficient granularity. uint256 private constant TOTAL_SHARES = MAX_UINT256 - (MAX_UINT256 % MAX_FRAGMENTS_SUPPLY); // MAX_SUPPLY = maximum integer < (sqrt(4*TOTAL_SHARES + 1) - 1) / 2 uint256 private constant MAX_SUPPLY = MAX_UINT128; uint256 private _totalSupply; uint256 public _sharesPerFragment; uint256 public _initialSharesPerFragment; mapping(address => uint256) private _shareBalances; // This is denominated in Fragments, because the shares-fragments conversion might change before // it's fully paid. mapping(address => mapping(address => uint256)) private _allowedFragments; /** * @param monetaryPolicy_ The address of the monetary policy contract to use for authentication. */ function setMonetaryPolicy(address monetaryPolicy_) external onlyOwner { monetaryPolicy = monetaryPolicy_; emit LogMonetaryPolicyUpdated(monetaryPolicy_); } /** * @dev Notifies Fragments contract about a new rebase cycle. * @param supplyDelta The number of new fragment tokens to add into circulation via expansion. * @return The total number of fragments after the supply adjustment. */ function rebase(uint256 epoch, int256 supplyDelta) external onlyMonetaryPolicy onlyAfterRebaseStart returns (uint256) { if (supplyDelta == 0) { emit LogRebase(epoch, _totalSupply); return _totalSupply; } if (supplyDelta < 0) { _totalSupply = _totalSupply.sub(uint256(supplyDelta.abs())); } else { _totalSupply = _totalSupply.add(uint256(supplyDelta)); } if (_totalSupply > MAX_SUPPLY) { _totalSupply = MAX_SUPPLY; } _sharesPerFragment = TOTAL_SHARES.div(_totalSupply); // From this point forward, _sharesPerFragment is taken as the source of truth. // We recalculate a new _totalSupply to be in agreement with the _sharesPerFragment // conversion rate. // This means our applied supplyDelta can deviate from the requested supplyDelta, // but this deviation is guaranteed to be < (_totalSupply^2)/(TOTAL_SHARES - _totalSupply). // // In the case of _totalSupply <= MAX_UINT128 (our current supply cap), this // deviation is guaranteed to be < 1, so we can omit this step. If the supply cap is // ever increased, it must be re-included. // NB: Digg will likely never reach the total supply cap as the total supply of BTC is // currently 21 million and MAX_UINT128 is many orders of magnitude greater. // _totalSupply = TOTAL_SHARES.div(_sharesPerFragment) emit LogRebase(epoch, _totalSupply); return _totalSupply; } function initialize(address owner_) public initializer { ERC20Detailed.initialize("Digg", "DIGG", uint8(DECIMALS)); Ownable.initialize(owner_); rebaseStartTime = 0; rebasePausedDeprecated = false; tokenPausedDeprecated = false; _totalSupply = MAX_FRAGMENTS_SUPPLY; _shareBalances[owner_] = TOTAL_SHARES; _sharesPerFragment = TOTAL_SHARES.div(_totalSupply); _initialSharesPerFragment = TOTAL_SHARES.div(_totalSupply); emit Transfer(address(0x0), owner_, _totalSupply); } /** * @return The total number of fragments. */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @return The total number of underlying shares. */ function totalShares() public view returns (uint256) { return TOTAL_SHARES; } /** * @param who The address to query. * @return The balance of the specified address. */ function balanceOf(address who) public view returns (uint256) { return _shareBalances[who].div(_sharesPerFragment); } /** * @param who The address to query. * @return The underlying shares of the specified address. */ function sharesOf(address who) public view returns (uint256) { return _shareBalances[who]; } /** * @param fragments Fragment value to convert. * @return The underlying share value of the specified fragment amount. */ function fragmentsToShares(uint256 fragments) public view returns (uint256) { return fragments.mul(_sharesPerFragment); } /** * @param shares Share value to convert. * @return The current fragment value of the specified underlying share amount. */ function sharesToFragments(uint256 shares) public view returns (uint256) { if (shares == 0) { return 0; } return shares.div(_sharesPerFragment); } /// @dev Scaled Shares are a user-friendly representation of shares function scaledSharesToShares(uint256 fragments) public view returns (uint256) { return fragments.mul(_initialSharesPerFragment).mul(10**SCALED_SHARES_EXTRA_DECIMALS); } function sharesToScaledShares(uint256 shares) public view returns (uint256) { if (shares == 0) { return 0; } return shares.div(_initialSharesPerFragment).mul(10**SCALED_SHARES_EXTRA_DECIMALS); } /** * @dev Transfer tokens to a specified address. * @param to The address to transfer to. * @param value The amount to be transferred. * @return True on success, false otherwise. */ function transfer(address to, uint256 value) public validRecipient(to) returns (bool) { uint256 shareValue = value.mul(_sharesPerFragment); _shareBalances[msg.sender] = _shareBalances[msg.sender].sub(shareValue); _shareBalances[to] = _shareBalances[to].add(shareValue); emit Transfer(msg.sender, to, value); return true; } /** * @dev Function to check the amount of tokens that an owner has allowed to a spender. * @param owner_ The address which owns the funds. * @param spender The address which will spend the funds. * @return The number of tokens still available for the spender. */ function allowance(address owner_, address spender) public view returns (uint256) { return _allowedFragments[owner_][spender]; } /** * @dev Transfer tokens from one address to another. * @param from The address you want to send tokens from. * @param to The address you want to transfer to. * @param value The amount of tokens to be transferred. */ function transferFrom( address from, address to, uint256 value ) public validRecipient(to) returns (bool) { _allowedFragments[from][msg.sender] = _allowedFragments[from][msg.sender].sub(value); uint256 shareValue = value.mul(_sharesPerFragment); _shareBalances[from] = _shareBalances[from].sub(shareValue); _shareBalances[to] = _shareBalances[to].add(shareValue); emit Transfer(from, to, value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of * msg.sender. This method is included for ERC20 compatibility. * increaseAllowance and decreaseAllowance should be used instead. * Changing an allowance with this method brings the risk that someone may transfer both * the old and the new allowance - if they are both greater than zero - if a transfer * transaction is mined before the later approve() call is mined. * * @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) { _allowedFragments[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /** * @dev Increase the amount of tokens that an owner has allowed to a spender. * This method should be used instead of approve() to avoid the double approval vulnerability * described above. * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _allowedFragments[msg.sender][spender] = _allowedFragments[msg.sender][spender].add(addedValue); emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]); return true; } /** * @dev Decrease the amount of tokens that an owner has allowed to a spender. * * @param spender The address which will spend the funds. * @param subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { uint256 oldValue = _allowedFragments[msg.sender][spender]; if (subtractedValue >= oldValue) { _allowedFragments[msg.sender][spender] = 0; } else { _allowedFragments[msg.sender][spender] = oldValue.sub(subtractedValue); } emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]); return true; } }
PLEASE READ BEFORE CHANGING ANY ACCOUNTING OR MATH Anytime there is division, there is a risk of numerical instability from rounding errors. In order to minimize this risk, we adhere to the following guidelines: 1) The conversion rate adopted is the number of shares that equals 1 fragment. The inverse rate must not be used--TOTAL_SHARES is always the numerator and _totalSupply is always the denominator. (i.e. If you want to convert shares to fragments instead of multiplying by the inverse rate, you should divide by the normal rate) 2) Share balances converted into Fragments are always rounded down (truncated). We make the following guarantees: - If address 'A' transfers x Fragments to address 'B'. A's resulting external balance will be decreased by precisely x Fragments, and B's external balance will be precisely increased by x Fragments. We do not guarantee that the sum of all balances equals the result of calling totalSupply(). This is because, for any conversion function 'f()' that has non-zero rounding error, f(x0) + f(x1) + ... + f(xn) is not always equal to f(x0 + x1 + ... xn). Used for authentication
contract UFragments is ERC20Detailed, Ownable { using SafeMath for uint256; using SafeMathInt for int256; event LogRebase(uint256 indexed epoch, uint256 totalSupply); event LogMonetaryPolicyUpdated(address monetaryPolicy); address public monetaryPolicy; uint256 public rebaseStartTime; modifier onlyMonetaryPolicy() { require(msg.sender == monetaryPolicy); _; } bool private rebasePausedDeprecated; bool private tokenPausedDeprecated; modifier validRecipient(address to) { require(to != address(0x0)); require(to != address(this)); _; } modifier onlyAfterRebaseStart() { require(now >= rebaseStartTime); _; } uint256 private constant DECIMALS = 9; uint256 private constant SCALED_SHARES_EXTRA_DECIMALS = 9; uint256 private constant MAX_UINT256 = ~uint256(0); uint256 private constant MAX_UINT128 = ~uint128(0); uint256 private constant MAX_FRAGMENTS_SUPPLY = 4000 * 10**DECIMALS; uint256 private _totalSupply; uint256 public _sharesPerFragment; uint256 public _initialSharesPerFragment; mapping(address => uint256) private _shareBalances; uint256 private constant TOTAL_SHARES = MAX_UINT256 - (MAX_UINT256 % MAX_FRAGMENTS_SUPPLY); uint256 private constant MAX_SUPPLY = MAX_UINT128; mapping(address => mapping(address => uint256)) private _allowedFragments; function setMonetaryPolicy(address monetaryPolicy_) external onlyOwner { monetaryPolicy = monetaryPolicy_; emit LogMonetaryPolicyUpdated(monetaryPolicy_); } function rebase(uint256 epoch, int256 supplyDelta) external onlyMonetaryPolicy onlyAfterRebaseStart returns (uint256) { if (supplyDelta == 0) { emit LogRebase(epoch, _totalSupply); return _totalSupply; } if (supplyDelta < 0) { _totalSupply = _totalSupply.sub(uint256(supplyDelta.abs())); _totalSupply = _totalSupply.add(uint256(supplyDelta)); } if (_totalSupply > MAX_SUPPLY) { _totalSupply = MAX_SUPPLY; } _sharesPerFragment = TOTAL_SHARES.div(_totalSupply); emit LogRebase(epoch, _totalSupply); return _totalSupply; } function rebase(uint256 epoch, int256 supplyDelta) external onlyMonetaryPolicy onlyAfterRebaseStart returns (uint256) { if (supplyDelta == 0) { emit LogRebase(epoch, _totalSupply); return _totalSupply; } if (supplyDelta < 0) { _totalSupply = _totalSupply.sub(uint256(supplyDelta.abs())); _totalSupply = _totalSupply.add(uint256(supplyDelta)); } if (_totalSupply > MAX_SUPPLY) { _totalSupply = MAX_SUPPLY; } _sharesPerFragment = TOTAL_SHARES.div(_totalSupply); emit LogRebase(epoch, _totalSupply); return _totalSupply; } function rebase(uint256 epoch, int256 supplyDelta) external onlyMonetaryPolicy onlyAfterRebaseStart returns (uint256) { if (supplyDelta == 0) { emit LogRebase(epoch, _totalSupply); return _totalSupply; } if (supplyDelta < 0) { _totalSupply = _totalSupply.sub(uint256(supplyDelta.abs())); _totalSupply = _totalSupply.add(uint256(supplyDelta)); } if (_totalSupply > MAX_SUPPLY) { _totalSupply = MAX_SUPPLY; } _sharesPerFragment = TOTAL_SHARES.div(_totalSupply); emit LogRebase(epoch, _totalSupply); return _totalSupply; } } else { function rebase(uint256 epoch, int256 supplyDelta) external onlyMonetaryPolicy onlyAfterRebaseStart returns (uint256) { if (supplyDelta == 0) { emit LogRebase(epoch, _totalSupply); return _totalSupply; } if (supplyDelta < 0) { _totalSupply = _totalSupply.sub(uint256(supplyDelta.abs())); _totalSupply = _totalSupply.add(uint256(supplyDelta)); } if (_totalSupply > MAX_SUPPLY) { _totalSupply = MAX_SUPPLY; } _sharesPerFragment = TOTAL_SHARES.div(_totalSupply); emit LogRebase(epoch, _totalSupply); return _totalSupply; } function initialize(address owner_) public initializer { ERC20Detailed.initialize("Digg", "DIGG", uint8(DECIMALS)); Ownable.initialize(owner_); rebaseStartTime = 0; rebasePausedDeprecated = false; tokenPausedDeprecated = false; _totalSupply = MAX_FRAGMENTS_SUPPLY; _shareBalances[owner_] = TOTAL_SHARES; _sharesPerFragment = TOTAL_SHARES.div(_totalSupply); _initialSharesPerFragment = TOTAL_SHARES.div(_totalSupply); emit Transfer(address(0x0), owner_, _totalSupply); } function totalSupply() public view returns (uint256) { return _totalSupply; } function totalShares() public view returns (uint256) { return TOTAL_SHARES; } function balanceOf(address who) public view returns (uint256) { return _shareBalances[who].div(_sharesPerFragment); } function sharesOf(address who) public view returns (uint256) { return _shareBalances[who]; } function fragmentsToShares(uint256 fragments) public view returns (uint256) { return fragments.mul(_sharesPerFragment); } function sharesToFragments(uint256 shares) public view returns (uint256) { if (shares == 0) { return 0; } return shares.div(_sharesPerFragment); } function sharesToFragments(uint256 shares) public view returns (uint256) { if (shares == 0) { return 0; } return shares.div(_sharesPerFragment); } function scaledSharesToShares(uint256 fragments) public view returns (uint256) { return fragments.mul(_initialSharesPerFragment).mul(10**SCALED_SHARES_EXTRA_DECIMALS); } function sharesToScaledShares(uint256 shares) public view returns (uint256) { if (shares == 0) { return 0; } return shares.div(_initialSharesPerFragment).mul(10**SCALED_SHARES_EXTRA_DECIMALS); } function sharesToScaledShares(uint256 shares) public view returns (uint256) { if (shares == 0) { return 0; } return shares.div(_initialSharesPerFragment).mul(10**SCALED_SHARES_EXTRA_DECIMALS); } function transfer(address to, uint256 value) public validRecipient(to) returns (bool) { uint256 shareValue = value.mul(_sharesPerFragment); _shareBalances[msg.sender] = _shareBalances[msg.sender].sub(shareValue); _shareBalances[to] = _shareBalances[to].add(shareValue); emit Transfer(msg.sender, to, value); return true; } function allowance(address owner_, address spender) public view returns (uint256) { return _allowedFragments[owner_][spender]; } function transferFrom( address from, address to, uint256 value ) public validRecipient(to) returns (bool) { _allowedFragments[from][msg.sender] = _allowedFragments[from][msg.sender].sub(value); uint256 shareValue = value.mul(_sharesPerFragment); _shareBalances[from] = _shareBalances[from].sub(shareValue); _shareBalances[to] = _shareBalances[to].add(shareValue); emit Transfer(from, to, value); return true; } function approve(address spender, uint256 value) public returns (bool) { _allowedFragments[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _allowedFragments[msg.sender][spender] = _allowedFragments[msg.sender][spender].add(addedValue); emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { uint256 oldValue = _allowedFragments[msg.sender][spender]; if (subtractedValue >= oldValue) { _allowedFragments[msg.sender][spender] = 0; _allowedFragments[msg.sender][spender] = oldValue.sub(subtractedValue); } emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { uint256 oldValue = _allowedFragments[msg.sender][spender]; if (subtractedValue >= oldValue) { _allowedFragments[msg.sender][spender] = 0; _allowedFragments[msg.sender][spender] = oldValue.sub(subtractedValue); } emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]); return true; } } else { }
985,070
[ 1, 52, 22357, 10746, 21203, 6469, 3388, 1360, 16743, 29437, 1360, 4869, 28394, 5502, 957, 1915, 353, 16536, 16, 1915, 353, 279, 18404, 434, 17409, 1804, 2967, 628, 13885, 1334, 18, 657, 1353, 358, 18935, 333, 18404, 16, 732, 1261, 14852, 358, 326, 3751, 9875, 14567, 30, 404, 13, 1021, 4105, 4993, 1261, 3838, 329, 353, 326, 1300, 434, 24123, 716, 1606, 404, 5481, 18, 565, 1021, 8322, 4993, 1297, 486, 506, 1399, 413, 28624, 67, 8325, 7031, 353, 3712, 326, 16730, 471, 389, 4963, 3088, 1283, 353, 565, 3712, 326, 15030, 18, 261, 77, 18, 73, 18, 971, 1846, 2545, 358, 1765, 24123, 358, 14656, 3560, 434, 565, 10194, 310, 635, 326, 8322, 4993, 16, 1846, 1410, 12326, 635, 326, 2212, 4993, 13, 576, 13, 25805, 324, 26488, 5970, 1368, 478, 2458, 1346, 854, 3712, 16729, 2588, 261, 23558, 690, 2934, 1660, 1221, 326, 3751, 28790, 30, 300, 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, 587, 27588, 353, 4232, 39, 3462, 40, 6372, 16, 14223, 6914, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 565, 1450, 14060, 10477, 1702, 364, 509, 5034, 31, 203, 203, 565, 871, 1827, 426, 1969, 12, 11890, 5034, 8808, 7632, 16, 2254, 5034, 2078, 3088, 1283, 1769, 203, 565, 871, 1827, 11415, 14911, 2582, 7381, 12, 2867, 31198, 2582, 1769, 203, 203, 565, 1758, 1071, 31198, 2582, 31, 203, 565, 2254, 5034, 1071, 283, 1969, 13649, 31, 203, 203, 203, 565, 9606, 1338, 11415, 14911, 2582, 1435, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 31198, 2582, 1769, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 565, 1426, 3238, 283, 1969, 28590, 13534, 31, 203, 565, 1426, 3238, 1147, 28590, 13534, 31, 203, 203, 565, 9606, 923, 18241, 12, 2867, 358, 13, 288, 203, 3639, 2583, 12, 869, 480, 1758, 12, 20, 92, 20, 10019, 203, 3639, 2583, 12, 869, 480, 1758, 12, 2211, 10019, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 565, 9606, 1338, 4436, 426, 1969, 1685, 1435, 288, 203, 3639, 2583, 12, 3338, 1545, 283, 1969, 13649, 1769, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 565, 2254, 5034, 3238, 5381, 25429, 55, 273, 2468, 31, 203, 565, 2254, 5034, 3238, 5381, 348, 3587, 6687, 67, 8325, 7031, 67, 22639, 67, 23816, 55, 273, 2468, 31, 203, 565, 2254, 5034, 3238, 5381, 4552, 67, 57, 3217, 5034, 273, 4871, 11890, 5034, 12, 20, 1769, 203, 565, 2254, 5034, 3238, 5381, 4552, 67, 2 ]
pragma solidity 0.5.8; import "../libraries/VersionUtils.sol"; import "../libraries/Util.sol"; import "../interfaces/IModule.sol"; import "../interfaces/IOracle.sol"; import "../interfaces/IPolymathRegistry.sol"; import "../interfaces/IModuleFactory.sol"; import "openzeppelin-solidity/contracts/token/ERC20/IERC20.sol"; import "openzeppelin-solidity/contracts/ownership/Ownable.sol"; import "../libraries/DecimalMath.sol"; /** * @title Interface that any module factory contract should implement * @notice Contract is abstract */ contract ModuleFactory is IModuleFactory, Ownable { IPolymathRegistry public polymathRegistry; string initialVersion; bytes32 public name; string public title; string public description; uint8[] typesData; bytes32[] tagsData; bool public isCostInPoly; uint256 public setupCost; string constant POLY_ORACLE = "StablePolyUsdOracle"; // @notice Allow only two variables to be stored // 1. lowerBound // 2. upperBound // @dev (0.0.0 will act as the wildcard) // @dev uint24 consists packed value of uint8 _major, uint8 _minor, uint8 _patch mapping(string => uint24) compatibleSTVersionRange; /** * @notice Constructor */ constructor(uint256 _setupCost, address _polymathRegistry, bool _isCostInPoly) public { setupCost = _setupCost; polymathRegistry = IPolymathRegistry(_polymathRegistry); isCostInPoly = _isCostInPoly; } /** * @notice Type of the Module factory */ function getTypes() external view returns(uint8[] memory) { return typesData; } /** * @notice Get the tags related to the module factory */ function getTags() external view returns(bytes32[] memory) { return tagsData; } /** * @notice Get the version related to the module factory */ function version() external view returns(string memory) { return initialVersion; } /** * @notice Used to change the fee of the setup cost * @param _setupCost new setup cost */ function changeSetupCost(uint256 _setupCost) public onlyOwner { emit ChangeSetupCost(setupCost, _setupCost); setupCost = _setupCost; } /** * @notice Used to change the currency and amount of setup cost * @param _setupCost new setup cost * @param _isCostInPoly new setup cost currency. USD or POLY */ function changeCostAndType(uint256 _setupCost, bool _isCostInPoly) public onlyOwner { emit ChangeSetupCost(setupCost, _setupCost); emit ChangeCostType(isCostInPoly, _isCostInPoly); setupCost = _setupCost; isCostInPoly = _isCostInPoly; } /** * @notice Updates the title of the ModuleFactory * @param _title New Title that will replace the old one. */ function changeTitle(string memory _title) public onlyOwner { require(bytes(_title).length > 0, "Invalid text"); title = _title; } /** * @notice Updates the description of the ModuleFactory * @param _description New description that will replace the old one. */ function changeDescription(string memory _description) public onlyOwner { require(bytes(_description).length > 0, "Invalid text"); description = _description; } /** * @notice Updates the name of the ModuleFactory * @param _name New name that will replace the old one. */ function changeName(bytes32 _name) public onlyOwner { require(_name != bytes32(0), "Invalid text"); name = _name; } /** * @notice Updates the tags of the ModuleFactory * @param _tagsData New list of tags */ function changeTags(bytes32[] memory _tagsData) public onlyOwner { require(_tagsData.length > 0, "Invalid text"); tagsData = _tagsData; } /** * @notice Function use to change the lower and upper bound of the compatible version st * @param _boundType Type of bound * @param _newVersion new version array */ function changeSTVersionBounds(string calldata _boundType, uint8[] calldata _newVersion) external onlyOwner { require( keccak256(abi.encodePacked(_boundType)) == keccak256(abi.encodePacked("lowerBound")) || keccak256( abi.encodePacked(_boundType) ) == keccak256(abi.encodePacked("upperBound")), "Invalid bound type" ); require(_newVersion.length == 3, "Invalid version"); if (compatibleSTVersionRange[_boundType] != uint24(0)) { uint8[] memory _currentVersion = VersionUtils.unpack(compatibleSTVersionRange[_boundType]); if (keccak256(abi.encodePacked(_boundType)) == keccak256(abi.encodePacked("lowerBound"))) { require(VersionUtils.lessThanOrEqual(_newVersion, _currentVersion), "Invalid version"); } else { require(VersionUtils.greaterThanOrEqual(_newVersion, _currentVersion), "Invalid version"); } } compatibleSTVersionRange[_boundType] = VersionUtils.pack(_newVersion[0], _newVersion[1], _newVersion[2]); emit ChangeSTVersionBound(_boundType, _newVersion[0], _newVersion[1], _newVersion[2]); } /** * @notice Used to get the lower bound * @return lower bound */ function getLowerSTVersionBounds() external view returns(uint8[] memory) { return VersionUtils.unpack(compatibleSTVersionRange["lowerBound"]); } /** * @notice Used to get the upper bound * @return upper bound */ function getUpperSTVersionBounds() external view returns(uint8[] memory) { return VersionUtils.unpack(compatibleSTVersionRange["upperBound"]); } /** * @notice Get the setup cost of the module */ function setupCostInPoly() public returns (uint256) { if (isCostInPoly) return setupCost; uint256 polyRate = IOracle(polymathRegistry.getAddress(POLY_ORACLE)).getPrice(); return DecimalMath.div(setupCost, polyRate); } /** * @notice Calculates fee in POLY */ function _takeFee() internal returns(uint256) { uint256 polySetupCost = setupCostInPoly(); address polyToken = polymathRegistry.getAddress("PolyToken"); if (polySetupCost > 0) { require(IERC20(polyToken).transferFrom(msg.sender, owner(), polySetupCost), "Insufficient allowance for module fee"); } return polySetupCost; } /** * @notice Used to initialize the module * @param _module Address of module * @param _data Data used for the intialization of the module factory variables */ function _initializeModule(address _module, bytes memory _data) internal { uint256 polySetupCost = _takeFee(); bytes4 initFunction = IModule(_module).getInitFunction(); if (initFunction != bytes4(0)) { require(Util.getSig(_data) == initFunction, "Provided data is not valid"); /*solium-disable-next-line security/no-low-level-calls*/ (bool success, ) = _module.call(_data); require(success, "Unsuccessful initialization"); } /*solium-disable-next-line security/no-block-members*/ emit GenerateModuleFromFactory(_module, name, address(this), msg.sender, setupCost, polySetupCost); } }
* @title Interface that any module factory contract should implement @notice Contract is abstract/ @notice Allow only two variables to be stored 1. lowerBound 2. upperBound @dev (0.0.0 will act as the wildcard) @dev uint24 consists packed value of uint8 _major, uint8 _minor, uint8 _patch
contract ModuleFactory is IModuleFactory, Ownable { IPolymathRegistry public polymathRegistry; string initialVersion; bytes32 public name; string public title; string public description; uint8[] typesData; bytes32[] tagsData; bool public isCostInPoly; uint256 public setupCost; string constant POLY_ORACLE = "StablePolyUsdOracle"; mapping(string => uint24) compatibleSTVersionRange; constructor(uint256 _setupCost, address _polymathRegistry, bool _isCostInPoly) public { setupCost = _setupCost; polymathRegistry = IPolymathRegistry(_polymathRegistry); isCostInPoly = _isCostInPoly; } function getTypes() external view returns(uint8[] memory) { return typesData; } function getTags() external view returns(bytes32[] memory) { return tagsData; } function version() external view returns(string memory) { return initialVersion; } function changeSetupCost(uint256 _setupCost) public onlyOwner { emit ChangeSetupCost(setupCost, _setupCost); setupCost = _setupCost; } function changeCostAndType(uint256 _setupCost, bool _isCostInPoly) public onlyOwner { emit ChangeSetupCost(setupCost, _setupCost); emit ChangeCostType(isCostInPoly, _isCostInPoly); setupCost = _setupCost; isCostInPoly = _isCostInPoly; } function changeTitle(string memory _title) public onlyOwner { require(bytes(_title).length > 0, "Invalid text"); title = _title; } function changeDescription(string memory _description) public onlyOwner { require(bytes(_description).length > 0, "Invalid text"); description = _description; } function changeName(bytes32 _name) public onlyOwner { require(_name != bytes32(0), "Invalid text"); name = _name; } function changeTags(bytes32[] memory _tagsData) public onlyOwner { require(_tagsData.length > 0, "Invalid text"); tagsData = _tagsData; } function changeSTVersionBounds(string calldata _boundType, uint8[] calldata _newVersion) external onlyOwner { require( keccak256(abi.encodePacked(_boundType)) == keccak256(abi.encodePacked("lowerBound")) || keccak256( abi.encodePacked(_boundType) ) == keccak256(abi.encodePacked("upperBound")), "Invalid bound type" ); require(_newVersion.length == 3, "Invalid version"); if (compatibleSTVersionRange[_boundType] != uint24(0)) { uint8[] memory _currentVersion = VersionUtils.unpack(compatibleSTVersionRange[_boundType]); if (keccak256(abi.encodePacked(_boundType)) == keccak256(abi.encodePacked("lowerBound"))) { require(VersionUtils.lessThanOrEqual(_newVersion, _currentVersion), "Invalid version"); require(VersionUtils.greaterThanOrEqual(_newVersion, _currentVersion), "Invalid version"); } } compatibleSTVersionRange[_boundType] = VersionUtils.pack(_newVersion[0], _newVersion[1], _newVersion[2]); emit ChangeSTVersionBound(_boundType, _newVersion[0], _newVersion[1], _newVersion[2]); } function changeSTVersionBounds(string calldata _boundType, uint8[] calldata _newVersion) external onlyOwner { require( keccak256(abi.encodePacked(_boundType)) == keccak256(abi.encodePacked("lowerBound")) || keccak256( abi.encodePacked(_boundType) ) == keccak256(abi.encodePacked("upperBound")), "Invalid bound type" ); require(_newVersion.length == 3, "Invalid version"); if (compatibleSTVersionRange[_boundType] != uint24(0)) { uint8[] memory _currentVersion = VersionUtils.unpack(compatibleSTVersionRange[_boundType]); if (keccak256(abi.encodePacked(_boundType)) == keccak256(abi.encodePacked("lowerBound"))) { require(VersionUtils.lessThanOrEqual(_newVersion, _currentVersion), "Invalid version"); require(VersionUtils.greaterThanOrEqual(_newVersion, _currentVersion), "Invalid version"); } } compatibleSTVersionRange[_boundType] = VersionUtils.pack(_newVersion[0], _newVersion[1], _newVersion[2]); emit ChangeSTVersionBound(_boundType, _newVersion[0], _newVersion[1], _newVersion[2]); } function changeSTVersionBounds(string calldata _boundType, uint8[] calldata _newVersion) external onlyOwner { require( keccak256(abi.encodePacked(_boundType)) == keccak256(abi.encodePacked("lowerBound")) || keccak256( abi.encodePacked(_boundType) ) == keccak256(abi.encodePacked("upperBound")), "Invalid bound type" ); require(_newVersion.length == 3, "Invalid version"); if (compatibleSTVersionRange[_boundType] != uint24(0)) { uint8[] memory _currentVersion = VersionUtils.unpack(compatibleSTVersionRange[_boundType]); if (keccak256(abi.encodePacked(_boundType)) == keccak256(abi.encodePacked("lowerBound"))) { require(VersionUtils.lessThanOrEqual(_newVersion, _currentVersion), "Invalid version"); require(VersionUtils.greaterThanOrEqual(_newVersion, _currentVersion), "Invalid version"); } } compatibleSTVersionRange[_boundType] = VersionUtils.pack(_newVersion[0], _newVersion[1], _newVersion[2]); emit ChangeSTVersionBound(_boundType, _newVersion[0], _newVersion[1], _newVersion[2]); } } else { function getLowerSTVersionBounds() external view returns(uint8[] memory) { return VersionUtils.unpack(compatibleSTVersionRange["lowerBound"]); } function getUpperSTVersionBounds() external view returns(uint8[] memory) { return VersionUtils.unpack(compatibleSTVersionRange["upperBound"]); } function setupCostInPoly() public returns (uint256) { if (isCostInPoly) return setupCost; uint256 polyRate = IOracle(polymathRegistry.getAddress(POLY_ORACLE)).getPrice(); return DecimalMath.div(setupCost, polyRate); } function _takeFee() internal returns(uint256) { uint256 polySetupCost = setupCostInPoly(); address polyToken = polymathRegistry.getAddress("PolyToken"); if (polySetupCost > 0) { require(IERC20(polyToken).transferFrom(msg.sender, owner(), polySetupCost), "Insufficient allowance for module fee"); } return polySetupCost; } function _takeFee() internal returns(uint256) { uint256 polySetupCost = setupCostInPoly(); address polyToken = polymathRegistry.getAddress("PolyToken"); if (polySetupCost > 0) { require(IERC20(polyToken).transferFrom(msg.sender, owner(), polySetupCost), "Insufficient allowance for module fee"); } return polySetupCost; } function _initializeModule(address _module, bytes memory _data) internal { uint256 polySetupCost = _takeFee(); bytes4 initFunction = IModule(_module).getInitFunction(); if (initFunction != bytes4(0)) { require(Util.getSig(_data) == initFunction, "Provided data is not valid"); (bool success, ) = _module.call(_data); require(success, "Unsuccessful initialization"); } function _initializeModule(address _module, bytes memory _data) internal { uint256 polySetupCost = _takeFee(); bytes4 initFunction = IModule(_module).getInitFunction(); if (initFunction != bytes4(0)) { require(Util.getSig(_data) == initFunction, "Provided data is not valid"); (bool success, ) = _module.call(_data); require(success, "Unsuccessful initialization"); } } emit GenerateModuleFromFactory(_module, name, address(this), msg.sender, setupCost, polySetupCost); }
12,850,200
[ 1, 1358, 716, 1281, 1605, 3272, 6835, 1410, 2348, 225, 13456, 353, 8770, 19, 225, 7852, 1338, 2795, 3152, 358, 506, 4041, 404, 18, 22656, 576, 18, 21663, 225, 261, 20, 18, 20, 18, 20, 903, 1328, 487, 326, 8531, 13, 225, 2254, 3247, 20915, 12456, 460, 434, 2254, 28, 389, 14019, 16, 2254, 28, 389, 17364, 16, 2254, 28, 389, 2272, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5924, 1733, 353, 467, 3120, 1733, 16, 14223, 6914, 288, 203, 203, 565, 2971, 355, 2942, 421, 4243, 1071, 2952, 2942, 421, 4243, 31, 203, 203, 565, 533, 2172, 1444, 31, 203, 565, 1731, 1578, 1071, 508, 31, 203, 565, 533, 1071, 2077, 31, 203, 565, 533, 1071, 2477, 31, 203, 203, 565, 2254, 28, 8526, 1953, 751, 31, 203, 565, 1731, 1578, 8526, 2342, 751, 31, 203, 203, 565, 1426, 1071, 353, 8018, 382, 12487, 31, 203, 565, 2254, 5034, 1071, 3875, 8018, 31, 203, 203, 565, 533, 5381, 19383, 61, 67, 916, 2226, 900, 273, 315, 30915, 12487, 3477, 72, 23601, 14432, 203, 203, 565, 2874, 12, 1080, 516, 2254, 3247, 13, 7318, 882, 1444, 2655, 31, 203, 203, 565, 3885, 12, 11890, 5034, 389, 8401, 8018, 16, 1758, 389, 3915, 2942, 421, 4243, 16, 1426, 389, 291, 8018, 382, 12487, 13, 1071, 288, 203, 3639, 3875, 8018, 273, 389, 8401, 8018, 31, 203, 3639, 2952, 2942, 421, 4243, 273, 2971, 355, 2942, 421, 4243, 24899, 3915, 2942, 421, 4243, 1769, 203, 3639, 353, 8018, 382, 12487, 273, 389, 291, 8018, 382, 12487, 31, 203, 565, 289, 203, 203, 565, 445, 20780, 1435, 3903, 1476, 1135, 12, 11890, 28, 8526, 3778, 13, 288, 203, 3639, 327, 1953, 751, 31, 203, 565, 289, 203, 203, 565, 445, 17388, 1435, 3903, 1476, 1135, 12, 3890, 1578, 8526, 3778, 13, 288, 203, 3639, 327, 2342, 751, 31, 203, 565, 289, 203, 203, 565, 445, 1177, 1435, 3903, 1476, 1135, 12, 1080, 3778, 13, 288, 2 ]
pragma solidity ^0.4.15; /** * @title Ownership interface * * Perminent ownership * * #created 01/10/2017 * #author Frank Bonnet */ contract IOwnership { /** * Returns true if `_account` is the current owner * * @param _account The address to test against */ function isOwner(address _account) constant returns (bool); /** * Gets the current owner * * @return address The current owner */ function getOwner() constant returns (address); } /** * @title Ownership * * Perminent ownership * * #created 01/10/2017 * #author Frank Bonnet */ contract Ownership is IOwnership { // Owner address internal owner; /** * The publisher is the inital owner */ function Ownership() { owner = msg.sender; } /** * Access is restricted to the current owner */ modifier only_owner() { require(msg.sender == owner); _; } /** * Returns true if `_account` is the current owner * * @param _account The address to test against */ function isOwner(address _account) public constant returns (bool) { return _account == owner; } /** * Gets the current owner * * @return address The current owner */ function getOwner() public constant returns (address) { return owner; } } /** * @title Transferable ownership interface * * Enhances ownership by allowing the current owner to * transfer ownership to a new owner * * #created 01/10/2017 * #author Frank Bonnet */ contract ITransferableOwnership { /** * Transfer ownership to `_newOwner` * * @param _newOwner The address of the account that will become the new owner */ function transferOwnership(address _newOwner); } /** * @title Transferable ownership * * Enhances ownership by allowing the current owner to * transfer ownership to a new owner * * #created 01/10/2017 * #author Frank Bonnet */ contract TransferableOwnership is ITransferableOwnership, Ownership { /** * Transfer ownership to `_newOwner` * * @param _newOwner The address of the account that will become the new owner */ function transferOwnership(address _newOwner) public only_owner { owner = _newOwner; } } /** * @title Multi-owned interface * * Interface that allows multiple owners * * #created 09/10/2017 * #author Frank Bonnet */ contract IMultiOwned { /** * Returns true if `_account` is an owner * * @param _account The address to test against */ function isOwner(address _account) constant returns (bool); /** * Returns the amount of owners * * @return The amount of owners */ function getOwnerCount() constant returns (uint); /** * Gets the owner at `_index` * * @param _index The index of the owner * @return The address of the owner found at `_index` */ function getOwnerAt(uint _index) constant returns (address); /** * Adds `_account` as a new owner * * @param _account The account to add as an owner */ function addOwner(address _account); /** * Removes `_account` as an owner * * @param _account The account to remove as an owner */ function removeOwner(address _account); } /** * @title Token retrieve interface * * Allows tokens to be retrieved from a contract * * #created 29/09/2017 * #author Frank Bonnet */ contract ITokenRetriever { /** * Extracts tokens from the contract * * @param _tokenContract The address of ERC20 compatible token */ function retrieveTokens(address _tokenContract); } /** * @title Token retrieve * * Allows tokens to be retrieved from a contract * * #created 18/10/2017 * #author Frank Bonnet */ contract TokenRetriever is ITokenRetriever { /** * Extracts tokens from the contract * * @param _tokenContract The address of ERC20 compatible token */ function retrieveTokens(address _tokenContract) public { IToken tokenInstance = IToken(_tokenContract); uint tokenBalance = tokenInstance.balanceOf(this); if (tokenBalance > 0) { tokenInstance.transfer(msg.sender, tokenBalance); } } } /** * @title Token observer interface * * Allows a token smart-contract to notify observers * when tokens are received * * #created 09/10/2017 * #author Frank Bonnet */ contract ITokenObserver { /** * Called by the observed token smart-contract in order * to notify the token observer when tokens are received * * @param _from The address that the tokens where send from * @param _value The amount of tokens that was received */ function notifyTokensReceived(address _from, uint _value); } /** * @title Abstract token observer * * Allows observers to be notified by an observed token smart-contract * when tokens are received * * #created 09/10/2017 * #author Frank Bonnet */ contract TokenObserver is ITokenObserver { /** * Called by the observed token smart-contract in order * to notify the token observer when tokens are received * * @param _from The address that the tokens where send from * @param _value The amount of tokens that was received */ function notifyTokensReceived(address _from, uint _value) public { onTokensReceived(msg.sender, _from, _value); } /** * Event handler * * Called by `_token` when a token amount is received * * @param _token The token contract that received the transaction * @param _from The account or contract that send the transaction * @param _value The value of tokens that where received */ function onTokensReceived(address _token, address _from, uint _value) internal; } /** * @title ERC20 compatible token interface * * - Implements ERC 20 Token standard * - Implements short address attack fix * * #created 29/09/2017 * #author Frank Bonnet */ contract IToken { /** * Get the total supply of tokens * * @return The total supply */ function totalSupply() constant returns (uint); /** * Get balance of `_owner` * * @param _owner The address from which the balance will be retrieved * @return The balance */ function balanceOf(address _owner) constant returns (uint); /** * Send `_value` token to `_to` from `msg.sender` * * @param _to The address of the recipient * @param _value The amount of token to be transferred * @return Whether the transfer was successful or not */ function transfer(address _to, uint _value) returns (bool); /** * Send `_value` token to `_to` from `_from` on the condition it is approved by `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value The amount of token to be transferred * @return Whether the transfer was successful or not */ function transferFrom(address _from, address _to, uint _value) returns (bool); /** * `msg.sender` approves `_spender` to spend `_value` tokens * * @param _spender The address of the account able to transfer the tokens * @param _value The amount of tokens to be approved for transfer * @return Whether the approval was successful or not */ function approve(address _spender, uint _value) returns (bool); /** * Get the amount of remaining tokens that `_spender` is allowed to spend from `_owner` * * @param _owner The address of the account owning tokens * @param _spender The address of the account able to transfer the tokens * @return Amount of remaining tokens allowed to spent */ function allowance(address _owner, address _spender) constant returns (uint); } /** * @title Dcorp Proxy * * Serves as a placeholder for the Dcorp funds, allowing the community the ability to vote on the acceptance of the VC platform, * and the transfer of token ownership. This mechanism is in place to allow the unlocking of the original DRP token, and to allow token * holders to convert to DRPU or DRPS. * This proxy is deployed upon receiving the Ether that is currently held by the DRP Crowdsale contract. * * #created 16/10/2017 * #author Frank Bonnet */ contract DcorpProxy is TokenObserver, TransferableOwnership, TokenRetriever { enum Stages { Deploying, Deployed, Executed } struct Balance { uint drps; uint drpu; uint index; } struct Vote { uint datetime; bool support; uint index; } struct Proposal { uint createdTimestamp; uint supportingWeight; uint rejectingWeight; mapping(address => Vote) votes; address[] voteIndex; uint index; } // State Stages private stage; // Settings uint private constant VOTING_DURATION = 7 days; uint private constant MIN_QUORUM = 5; // 5% // Alocated balances mapping (address => Balance) private allocated; address[] private allocatedIndex; // Proposals mapping(address => Proposal) private proposals; address[] private proposalIndex; // Tokens IToken private drpsToken; IToken private drpuToken; // Crowdsale address private drpCrowdsale; uint public drpCrowdsaleRecordedBalance; /** * Require that the proxy is in `_stage` */ modifier only_at_stage(Stages _stage) { require(stage == _stage); _; } /** * Require `_token` to be one of the drp tokens * * @param _token The address to test against */ modifier only_accepted_token(address _token) { require(_token == address(drpsToken) || _token == address(drpuToken)); _; } /** * Require that `_token` is not one of the drp tokens * * @param _token The address to test against */ modifier not_accepted_token(address _token) { require(_token != address(drpsToken) && _token != address(drpuToken)); _; } /** * Require that sender has more than zero tokens */ modifier only_token_holder() { require(allocated[msg.sender].drps > 0 || allocated[msg.sender].drpu > 0); _; } /** * Require `_proposedAddress` to have been proposed already * * @param _proposedAddress Address that needs to be proposed */ modifier only_proposed(address _proposedAddress) { require(isProposed(_proposedAddress)); _; } /** * Require that the voting period for the proposal has * not yet ended * * @param _proposedAddress Address that was proposed */ modifier only_during_voting_period(address _proposedAddress) { require(now <= proposals[_proposedAddress].createdTimestamp + VOTING_DURATION); _; } /** * Require that the voting period for the proposal has ended * * @param _proposedAddress Address that was proposed */ modifier only_after_voting_period(address _proposedAddress) { require(now > proposals[_proposedAddress].createdTimestamp + VOTING_DURATION); _; } /** * Require that the proposal is supported * * @param _proposedAddress Address that was proposed */ modifier only_when_supported(address _proposedAddress) { require(isSupported(_proposedAddress, false)); _; } /** * Construct the proxy * * @param _drpsToken The new security token * @param _drpuToken The new utility token * @param _drpCrowdsale Proxy accepts and requires ether from the crowdsale */ function DcorpProxy(address _drpsToken, address _drpuToken, address _drpCrowdsale) { drpsToken = IToken(_drpsToken); drpuToken = IToken(_drpuToken); drpCrowdsale = _drpCrowdsale; drpCrowdsaleRecordedBalance = _drpCrowdsale.balance; stage = Stages.Deploying; } /** * Returns whether the proxy is being deployed * * @return Whether the proxy is in the deploying stage */ function isDeploying() public constant returns (bool) { return stage == Stages.Deploying; } /** * Returns whether the proxy is deployed. The proxy is deployed * when it receives Ether from the drp crowdsale contract * * @return Whether the proxy is deployed */ function isDeployed() public constant returns (bool) { return stage == Stages.Deployed; } /** * Returns whether a proposal, and with it the proxy itself, is * already executed or not * * @return Whether the proxy is executed */ function isExecuted() public constant returns (bool) { return stage == Stages.Executed; } /** * Accept eth from the crowdsale while deploying */ function () public payable only_at_stage(Stages.Deploying) { require(msg.sender == drpCrowdsale); } /** * Deploy the proxy */ function deploy() only_owner only_at_stage(Stages.Deploying) { require(this.balance >= drpCrowdsaleRecordedBalance); stage = Stages.Deployed; } /** * Returns the combined total supply of all drp tokens * * @return The combined total drp supply */ function getTotalSupply() public constant returns (uint) { uint sum = 0; sum += drpsToken.totalSupply(); sum += drpuToken.totalSupply(); return sum; } /** * Returns true if `_owner` has a balance allocated * * @param _owner The account that the balance is allocated for * @return True if there is a balance that belongs to `_owner` */ function hasBalance(address _owner) public constant returns (bool) { return allocatedIndex.length > 0 && _owner == allocatedIndex[allocated[_owner].index]; } /** * Get the allocated drps token balance of `_owner` * * @param _token The address to test against * @param _owner The address from which the allocated token balance will be retrieved * @return The allocated drps token balance */ function balanceOf(address _token, address _owner) public constant returns (uint) { uint balance = 0; if (address(drpsToken) == _token) { balance = allocated[_owner].drps; } else if (address(drpuToken) == _token) { balance = allocated[_owner].drpu; } return balance; } /** * Returns true if `_proposedAddress` is already proposed * * @param _proposedAddress Address that was proposed * @return Whether `_proposedAddress` is already proposed */ function isProposed(address _proposedAddress) public constant returns (bool) { return proposalIndex.length > 0 && _proposedAddress == proposalIndex[proposals[_proposedAddress].index]; } /** * Returns the how many proposals where made * * @return The amount of proposals */ function getProposalCount() public constant returns (uint) { return proposalIndex.length; } /** * Propose the transfer token ownership and all funds to `_proposedAddress` * * @param _proposedAddress The proposed DCORP address */ function propose(address _proposedAddress) public only_owner only_at_stage(Stages.Deployed) { require(!isProposed(_proposedAddress)); // Add proposal Proposal storage p = proposals[_proposedAddress]; p.createdTimestamp = now; p.index = proposalIndex.push(_proposedAddress) - 1; } /** * Gets the voting duration, the amount of time voting * is allowed * * @return Voting duration */ function getVotingDuration() public constant returns (uint) { return VOTING_DURATION; } /** * Gets the number of votes towards a proposal * * @param _proposedAddress The proposed DCORP address * @return uint Vote count */ function getVoteCount(address _proposedAddress) public constant returns (uint) { return proposals[_proposedAddress].voteIndex.length; } /** * Returns true if `_account` has voted on the proposal * * @param _proposedAddress The proposed DCORP address * @param _account The key (address) that maps to the vote * @return bool Whether `_account` has voted on the proposal */ function hasVoted(address _proposedAddress, address _account) public constant returns (bool) { bool voted = false; if (getVoteCount(_proposedAddress) > 0) { Proposal storage p = proposals[_proposedAddress]; voted = p.voteIndex[p.votes[_account].index] == _account; } return voted; } /** * Returns true if `_account` supported the proposal and returns * false if `_account` is opposed to the proposal * * Does not check if `_account` had voted, use hasVoted() * * @param _proposedAddress The proposed DCORP address * @param _account The key (address) that maps to the vote * @return bool Supported */ function getVote(address _proposedAddress, address _account) public constant returns (bool) { return proposals[_proposedAddress].votes[_account].support; } /** * Allows a token holder to vote on a proposal * * @param _proposedAddress The proposed DCORP address * @param _support True if supported */ function vote(address _proposedAddress, bool _support) public only_at_stage(Stages.Deployed) only_proposed(_proposedAddress) only_during_voting_period(_proposedAddress) only_token_holder { Proposal storage p = proposals[_proposedAddress]; Balance storage b = allocated[msg.sender]; // Register vote if (!hasVoted(_proposedAddress, msg.sender)) { p.votes[msg.sender] = Vote( now, _support, p.voteIndex.push(msg.sender) - 1); // Register weight if (_support) { p.supportingWeight += b.drps + b.drpu; } else { p.rejectingWeight += b.drps + b.drpu; } } else { Vote storage v = p.votes[msg.sender]; if (v.support != _support) { // Register changed weight if (_support) { p.supportingWeight += b.drps + b.drpu; p.rejectingWeight -= b.drps + b.drpu; } else { p.rejectingWeight += b.drps + b.drpu; p.supportingWeight -= b.drps + b.drpu; } v.support = _support; v.datetime = now; } } } /** * Returns the current voting results for a proposal * * @param _proposedAddress The proposed DCORP address * @return supported, rejected */ function getVotingResult(address _proposedAddress) public constant returns (uint, uint) { Proposal storage p = proposals[_proposedAddress]; return (p.supportingWeight, p.rejectingWeight); } /** * Returns true if the proposal is supported * * @param _proposedAddress The proposed DCORP address * @param _strict If set to true the function requires that the voting period is ended * @return bool Supported */ function isSupported(address _proposedAddress, bool _strict) public constant returns (bool) { Proposal storage p = proposals[_proposedAddress]; bool supported = false; if (!_strict || now > p.createdTimestamp + VOTING_DURATION) { var (support, reject) = getVotingResult(_proposedAddress); supported = support > reject; if (supported) { supported = support + reject >= getTotalSupply() * MIN_QUORUM / 100; } } return supported; } /** * Executes the proposal * * Should only be called after the voting period and * when the proposal is supported * * @param _acceptedAddress The accepted DCORP address * @return bool Success */ function execute(address _acceptedAddress) public only_owner only_at_stage(Stages.Deployed) only_proposed(_acceptedAddress) only_after_voting_period(_acceptedAddress) only_when_supported(_acceptedAddress) { // Mark as executed stage = Stages.Executed; // Add accepted address as token owner IMultiOwned(drpsToken).addOwner(_acceptedAddress); IMultiOwned(drpuToken).addOwner(_acceptedAddress); // Remove self token as owner IMultiOwned(drpsToken).removeOwner(this); IMultiOwned(drpuToken).removeOwner(this); // Transfer Eth (safe because we don't know how much gas is used counting votes) uint balanceBefore = _acceptedAddress.balance; uint balanceToSend = this.balance; _acceptedAddress.transfer(balanceToSend); // Assert balances assert(balanceBefore + balanceToSend == _acceptedAddress.balance); assert(this.balance == 0); } /** * Event handler that initializes the token conversion * * Called by `_token` when a token amount is received on * the address of this token changer * * @param _token The token contract that received the transaction * @param _from The account or contract that send the transaction * @param _value The value of tokens that where received */ function onTokensReceived(address _token, address _from, uint _value) internal only_at_stage(Stages.Deployed) only_accepted_token(_token) { require(_token == msg.sender); // Allocate tokens if (!hasBalance(_from)) { allocated[_from] = Balance( 0, 0, allocatedIndex.push(_from) - 1); } Balance storage b = allocated[_from]; if (_token == address(drpsToken)) { b.drps += _value; } else { b.drpu += _value; } // Increase weight _adjustWeight(_from, _value, true); } /** * Withdraw DRPS tokens from the proxy and reduce the * owners weight accordingly * * @param _value The amount of DRPS tokens to withdraw */ function withdrawDRPS(uint _value) public { Balance storage b = allocated[msg.sender]; // Require sufficient balance require(b.drps >= _value); require(b.drps - _value <= b.drps); // Update balance b.drps -= _value; // Reduce weight _adjustWeight(msg.sender, _value, false); // Call external if (!drpsToken.transfer(msg.sender, _value)) { revert(); } } /** * Withdraw DRPU tokens from the proxy and reduce the * owners weight accordingly * * @param _value The amount of DRPU tokens to withdraw */ function withdrawDRPU(uint _value) public { Balance storage b = allocated[msg.sender]; // Require sufficient balance require(b.drpu >= _value); require(b.drpu - _value <= b.drpu); // Update balance b.drpu -= _value; // Reduce weight _adjustWeight(msg.sender, _value, false); // Call external if (!drpuToken.transfer(msg.sender, _value)) { revert(); } } /** * Failsafe mechanism * * Allows the owner to retrieve tokens (other than DRPS and DRPU tokens) from the contract that * might have been send there by accident * * @param _tokenContract The address of ERC20 compatible token */ function retrieveTokens(address _tokenContract) public only_owner not_accepted_token(_tokenContract) { super.retrieveTokens(_tokenContract); } /** * Adjust voting weight in ongoing proposals on which `_owner` * has already voted * * @param _owner The owner of the weight * @param _value The amount of weight that is adjusted * @param _increase Indicated whether the weight is increased or decreased */ function _adjustWeight(address _owner, uint _value, bool _increase) private { for (uint i = proposalIndex.length; i > 0; i--) { Proposal storage p = proposals[proposalIndex[i - 1]]; if (now > p.createdTimestamp + VOTING_DURATION) { break; // Last active proposal } if (hasVoted(proposalIndex[i - 1], _owner)) { if (p.votes[_owner].support) { if (_increase) { p.supportingWeight += _value; } else { p.supportingWeight -= _value; } } else { if (_increase) { p.rejectingWeight += _value; } else { p.rejectingWeight -= _value; } } } } } }
* Require `_proposedAddress` to have been proposed already @param _proposedAddress Address that needs to be proposed/
modifier only_proposed(address _proposedAddress) { require(isProposed(_proposedAddress)); _; }
12,807,817
[ 1, 8115, 1375, 67, 685, 7423, 1887, 68, 358, 1240, 2118, 20084, 1818, 225, 389, 685, 7423, 1887, 5267, 716, 4260, 358, 506, 20084, 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, 9606, 1338, 67, 685, 7423, 12, 2867, 389, 685, 7423, 1887, 13, 288, 203, 3639, 2583, 12, 291, 626, 7423, 24899, 685, 7423, 1887, 10019, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x88E51D12D75180556a5FD59770d62F8adf7Fa703/sources/AywakeToken.sol
Check if grant was revokable
require(grant.revokable);
9,424,951
[ 1, 1564, 309, 7936, 1703, 5588, 601, 429, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 2583, 12, 16243, 18, 9083, 601, 429, 1769, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.6.0; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "./IExternalStake.sol"; contract SDAOBondedTokenStake is IExternalStake, Ownable, ReentrancyGuard{ using SafeMath for uint256; ERC20 public token; // Address of token contract and same used for rewards ERC20 public bonusToken; // Address of bonus token contract struct StakeInfo { bool exist; uint256 amount; uint256 rewardComputeIndex; uint256 bonusAmount; } // Staking period timestamp (Debatable on timestamp vs blocknumber - went with timestamp) struct StakePeriod { uint256 startPeriod; uint256 submissionEndPeriod; uint256 endPeriod; uint256 maxStake; uint256 windowRewardAmount; uint256 windowMaxAmount; } address public tokenOperator; // Address to manage the Stake uint256 public maxAirDropStakeBlocks; // Block numbers to complete the airDrop Auto Stakes mapping (address => uint256) public balances; // Useer Token balance in the contract uint256 public currentStakeMapIndex; // Current Stake Index to avoid math calc in all methods mapping (uint256 => StakePeriod) public stakeMap; // List of Stake Holders address[] stakeHolders; // All Stake Holders mapping(address => StakeInfo) stakeHolderInfo; // To store the total stake in a window uint256 public windowTotalStake; // Events event NewOperator(address tokenOperator); event WithdrawToken(address indexed tokenOperator, uint256 amount); event OpenForStake(uint256 indexed stakeIndex, address indexed tokenOperator, uint256 startPeriod, uint256 endPeriod, uint256 rewardAmount); event SubmitStake(uint256 indexed stakeIndex, address indexed staker, uint256 stakeAmount); event WithdrawStake(uint256 indexed stakeIndex, address indexed staker, uint256 stakeAmount, uint256 bonusAmount); event ClaimStake(uint256 indexed stakeIndex, address indexed staker, uint256 totalAmount, uint256 bonusAmount); event AddReward(address indexed staker, uint256 indexed stakeIndex, address tokenOperator, uint256 stakeAmount, uint256 rewardAmount, uint256 windowTotalStake); // Modifiers modifier onlyOperator() { require( msg.sender == tokenOperator, "Only operator can call this function." ); _; } // Token Operator should be able to do auto renewal modifier allowSubmission() { require( now >= stakeMap[currentStakeMapIndex].startPeriod && now <= stakeMap[currentStakeMapIndex].submissionEndPeriod, "Staking at this point not allowed" ); _; } modifier validStakeLimit(address staker, uint256 stakeAmount) { uint256 stakerTotalStake; stakerTotalStake = stakeAmount.add(stakeHolderInfo[staker].amount); // Check for Max Stake per Wallet and stake window max limit require( stakeAmount > 0 && stakerTotalStake <= stakeMap[currentStakeMapIndex].maxStake && windowTotalStake.add(stakeAmount) <= stakeMap[currentStakeMapIndex].windowMaxAmount, "Exceeding max limits" ); _; } // Check for claim - Stake Window should be either in submission phase or after end period modifier allowClaimStake() { require( (now >= stakeMap[currentStakeMapIndex].startPeriod && now <= stakeMap[currentStakeMapIndex].submissionEndPeriod && stakeHolderInfo[msg.sender].amount > 0) || (now > stakeMap[currentStakeMapIndex].endPeriod && stakeHolderInfo[msg.sender].amount > 0), "Invalid claim request"); _; } constructor(address _token, uint256 _maxAirDropStakeBlocks) public { token = ERC20(_token); tokenOperator = msg.sender; currentStakeMapIndex = 0; windowTotalStake = 0; maxAirDropStakeBlocks = _maxAirDropStakeBlocks.add(block.number); } function updateOperator(address newOperator) external onlyOwner { require(newOperator != address(0), "Invalid operator address"); tokenOperator = newOperator; emit NewOperator(newOperator); } function withdrawToken(uint256 value) external onlyOperator { // Check if contract is having required balance require(token.balanceOf(address(this)) >= value, "Not enough balance in the contract"); require(token.transfer(msg.sender, value), "Unable to transfer token to the operator account"); emit WithdrawToken(tokenOperator, value); } // To set the bonus token for future needs function setBonusToken(address _bonusToken) external onlyOwner { require(_bonusToken != address(0), "Invalid bonus token"); bonusToken = ERC20(_bonusToken); } function openForStake(uint256 _startPeriod, uint256 _submissionEndPeriod, uint256 _endPeriod, uint256 _windowRewardAmount, uint256 _maxStake, uint256 _windowMaxAmount) external onlyOperator { // Check Input Parameters require(_startPeriod >= now && _startPeriod < _submissionEndPeriod && _submissionEndPeriod < _endPeriod, "Invalid stake period"); require(_windowRewardAmount > 0 && _maxStake > 0 && _windowMaxAmount > 0, "Invalid inputs" ); // Check Stake in Progress require(currentStakeMapIndex == 0 || (now > stakeMap[currentStakeMapIndex].submissionEndPeriod && _startPeriod >= stakeMap[currentStakeMapIndex].endPeriod), "Cannot have more than one stake request at a time"); // Move the staking period to next one currentStakeMapIndex = currentStakeMapIndex + 1; StakePeriod memory stakePeriod; // Set Staking attributes stakePeriod.startPeriod = _startPeriod; stakePeriod.submissionEndPeriod = _submissionEndPeriod; stakePeriod.endPeriod = _endPeriod; stakePeriod.windowRewardAmount = _windowRewardAmount; stakePeriod.maxStake = _maxStake; stakePeriod.windowMaxAmount = _windowMaxAmount; stakeMap[currentStakeMapIndex] = stakePeriod; // Add the current window reward to the window total stake windowTotalStake = windowTotalStake.add(_windowRewardAmount); emit OpenForStake(currentStakeMapIndex, msg.sender, _startPeriod, _endPeriod, _windowRewardAmount); } // To add the Stake Holder function _createStake(address staker, uint256 stakeAmount) internal returns(bool) { StakeInfo storage stakeInfo = stakeHolderInfo[staker]; // Check if the user already staked in the past if(stakeInfo.exist) { stakeInfo.amount = stakeInfo.amount.add(stakeAmount); } else { StakeInfo memory req; // Create a new stake request req.exist = true; req.amount = stakeAmount; req.rewardComputeIndex = 0; // Add to the Stake Holders List stakeHolderInfo[staker] = req; // Add to the Stake Holders List stakeHolders.push(staker); } return true; } // To submit a new stake for the current window - This function left as is for backward compatability with existing DApps function submitStake(uint256 stakeAmount) external allowSubmission validStakeLimit(msg.sender, stakeAmount) { // Transfer the Tokens to Contract require(token.transferFrom(msg.sender, address(this), stakeAmount), "Unable to transfer token to the contract"); _createStake(msg.sender, stakeAmount); // Update the User balance balances[msg.sender] = balances[msg.sender].add(stakeAmount); // Update current stake period total stake - For Auto Approvals windowTotalStake = windowTotalStake.add(stakeAmount); emit SubmitStake(currentStakeMapIndex, msg.sender, stakeAmount); } // To Submit a new stakeFor in the current window - Can be called from the other contracts like airdrop function submitStakeFor(address staker, uint256 stakeAmount) external virtual override allowSubmission validStakeLimit(staker, stakeAmount) nonReentrant returns(bool) { // Check for the stakerFor Address require(staker != address(0), "Invalid staker"); // Transfer the Tokens to Contract require(token.transferFrom(msg.sender, address(this), stakeAmount), "Unable to transfer token to the contract"); _createStake(staker, stakeAmount); // Update the User balance balances[staker] = balances[staker].add(stakeAmount); // Update current stake period total stake - For Auto Approvals windowTotalStake = windowTotalStake.add(stakeAmount); emit SubmitStake(currentStakeMapIndex, staker, stakeAmount); return true; } // To withdraw stake during submission phase function withdrawStake(uint256 stakeAmount) external allowClaimStake nonReentrant{ //require( // (now >= stakeMap[stakeMapIndex].startPeriod && now <= stakeMap[stakeMapIndex].submissionEndPeriod), // "Stake withdraw at this point is not allowed" //); StakeInfo storage stakeInfo = stakeHolderInfo[msg.sender]; // Validate the input Stake Amount require(stakeAmount > 0 && stakeInfo.amount >= stakeAmount, "Cannot withdraw beyond stake amount"); uint256 bonusAmount; // Update the staker balance in the staking window stakeInfo.amount = stakeInfo.amount.sub(stakeAmount); bonusAmount = stakeInfo.bonusAmount; stakeInfo.bonusAmount = 0; // Update the User balance balances[msg.sender] = balances[msg.sender].sub(stakeAmount); // Update current stake period total stake - For Auto Approvals windowTotalStake = windowTotalStake.sub(stakeAmount); // Return to User Wallet require(token.transfer(msg.sender, stakeAmount), "Unable to transfer token to the account"); // Call the bonus transfer function - Should transfer only if set if(address(bonusToken) != address(0) && bonusAmount > 0) { require(bonusToken.transfer(msg.sender, bonusAmount), "Unable to transfer bonus token to the account"); } emit WithdrawStake(currentStakeMapIndex, msg.sender, stakeAmount, bonusAmount); } // To claim from the stake window function claimStake() external allowClaimStake nonReentrant{ StakeInfo storage stakeInfo = stakeHolderInfo[msg.sender]; uint256 stakeAmount; uint256 bonusAmount; // No more stake windows or in submission phase stakeAmount = stakeInfo.amount; bonusAmount = stakeInfo.bonusAmount; stakeInfo.amount = 0; stakeInfo.bonusAmount = 0; // Update current stake period total stake windowTotalStake = windowTotalStake.sub(stakeAmount); // Check for balance in the contract require(token.balanceOf(address(this)) >= stakeAmount, "Not enough balance in the contract"); // Update the User Balance balances[msg.sender] = balances[msg.sender].sub(stakeAmount); // Call the transfer function require(token.transfer(msg.sender, stakeAmount), "Unable to transfer token back to the account"); // Call the bonus transfer function - Should transfer only if set if(address(bonusToken) != address(0) && bonusAmount > 0) { require(bonusToken.transfer(msg.sender, bonusAmount), "Unable to transfer bonus token to the account"); } emit ClaimStake(currentStakeMapIndex, msg.sender, stakeAmount, bonusAmount); } function _calculateRewardAmount(uint256 stakeMapIndex, uint256 stakeAmount) internal view returns(uint256) { uint256 calcRewardAmount; if(windowTotalStake > stakeMap[stakeMapIndex].windowRewardAmount) { calcRewardAmount = stakeAmount.mul(stakeMap[stakeMapIndex].windowRewardAmount).div(windowTotalStake.sub(stakeMap[stakeMapIndex].windowRewardAmount)); } return calcRewardAmount; } // Update reward for staker in the respective stake window function computeAndAddReward(uint256 stakeMapIndex, address staker, uint256 stakeBonusAmount) public onlyOperator returns(bool) { // Check for the Incubation Period require( now > stakeMap[stakeMapIndex].submissionEndPeriod && now < stakeMap[stakeMapIndex].endPeriod, "Reward cannot be added now" ); StakeInfo storage stakeInfo = stakeHolderInfo[staker]; // Check if reward already computed require(stakeInfo.amount > 0 && stakeInfo.rewardComputeIndex != stakeMapIndex, "Invalid reward request"); // Calculate the totalAmount uint256 totalAmount; uint256 rewardAmount; // Calculate the reward amount for the current window totalAmount = stakeInfo.amount; rewardAmount = _calculateRewardAmount(stakeMapIndex, totalAmount); totalAmount = totalAmount.add(rewardAmount); // Add the reward amount stakeInfo.amount = totalAmount; // Add the bonus Amount stakeInfo.bonusAmount = stakeInfo.bonusAmount.add(stakeBonusAmount); // Update the reward compute index to avoid mulitple addition stakeInfo.rewardComputeIndex = stakeMapIndex; // Update the User Balance balances[staker] = balances[staker].add(rewardAmount); emit AddReward(staker, stakeMapIndex, tokenOperator, totalAmount, rewardAmount, windowTotalStake); return true; } function updateRewards(uint256 stakeMapIndex, address[] calldata staker, uint256 stakeBonusAmount) external onlyOperator { for(uint256 indx = 0; indx < staker.length; indx++) { require(computeAndAddReward(stakeMapIndex, staker[indx], stakeBonusAmount)); } } // AirDrop to Stake - Load existing stakes from Air Drop function airDropStakes(uint256 stakeMapIndex, address[] calldata staker, uint256[] calldata stakeAmount) external onlyOperator { // Add check for Block Number to restrict air drop auto stake phase after certain block number require(block.number < maxAirDropStakeBlocks, "Exceeds airdrop auto stake phase"); // Check Input Parameters require(staker.length == stakeAmount.length, "Invalid Input Arrays"); // Stakers should be for current window require(currentStakeMapIndex == stakeMapIndex, "Invalid Stake Window Index"); for(uint256 indx = 0; indx < staker.length; indx++) { StakeInfo memory req; // Create a stake request with amount req.exist = true; req.amount = stakeAmount[indx]; req.rewardComputeIndex = 0; // Add to the Stake Holders List stakeHolderInfo[staker[indx]] = req; // Add to the Stake Holders List stakeHolders.push(staker[indx]); // Update the User balance balances[staker[indx]] = stakeAmount[indx]; // Update current stake period total stake - Along with Reward windowTotalStake = windowTotalStake.add(stakeAmount[indx]); } } // Getter Functions function getStakeHolders() external view returns(address[] memory) { return stakeHolders; } function getStakeInfo(address staker) external view returns (bool found, uint256 amount, uint256 rewardComputeIndex, uint256 bonusAmount) { StakeInfo memory stakeInfo = stakeHolderInfo[staker]; found = false; if(stakeInfo.exist) { found = true; } amount = stakeInfo.amount; rewardComputeIndex = stakeInfo.rewardComputeIndex; bonusAmount = stakeInfo.bonusAmount; } }
Check for claim - Stake Window should be either in submission phase or after end period
modifier allowClaimStake() { require( (now >= stakeMap[currentStakeMapIndex].startPeriod && now <= stakeMap[currentStakeMapIndex].submissionEndPeriod && stakeHolderInfo[msg.sender].amount > 0) || (now > stakeMap[currentStakeMapIndex].endPeriod && stakeHolderInfo[msg.sender].amount > 0), "Invalid claim request"); _; } constructor(address _token, uint256 _maxAirDropStakeBlocks) public
12,543,183
[ 1, 1564, 364, 7516, 300, 934, 911, 6076, 1410, 506, 3344, 316, 8515, 6855, 578, 1839, 679, 3879, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 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, 9606, 1699, 9762, 510, 911, 1435, 288, 203, 203, 3639, 2583, 12, 203, 1850, 261, 3338, 1545, 384, 911, 863, 63, 2972, 510, 911, 863, 1016, 8009, 1937, 5027, 597, 2037, 1648, 384, 911, 863, 63, 2972, 510, 911, 863, 1016, 8009, 12684, 1638, 5027, 597, 384, 911, 6064, 966, 63, 3576, 18, 15330, 8009, 8949, 405, 374, 13, 747, 7010, 1850, 261, 3338, 405, 384, 911, 863, 63, 2972, 510, 911, 863, 1016, 8009, 409, 5027, 597, 384, 911, 6064, 966, 63, 3576, 18, 15330, 8009, 8949, 405, 374, 3631, 315, 1941, 7516, 590, 8863, 203, 3639, 389, 31, 203, 203, 565, 289, 203, 203, 565, 3885, 12, 2867, 389, 2316, 16, 2254, 5034, 389, 1896, 29752, 7544, 510, 911, 6450, 13, 203, 565, 1071, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/44787/0x0192b56c549f8308689fAfF09DA95b919EaB801E/sources/src/diamond/libraries/AppStorage.sol
* @dev Throws if the contract is not paused./
function _requirePaused() internal view virtual { require(s.paused, "Pausable: not paused"); }
13,252,560
[ 1, 21845, 309, 326, 6835, 353, 486, 17781, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 6528, 28590, 1435, 2713, 1476, 5024, 288, 203, 3639, 2583, 12, 87, 18, 8774, 3668, 16, 315, 16507, 16665, 30, 486, 17781, 8863, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.16; import "./CToken.sol"; interface IFlashloanReceiver { function executeOperation(address sender, address underlying, uint amount, uint fee, bytes calldata params) external; } /** * @title Compound's CCapableErc20 Contract * @notice CTokens which wrap an EIP-20 underlying * @author Compound */ contract CCapableErc20 is CToken, CCapableErc20Interface, CCapableDelegateInterface { event Flashloan(address indexed receiver, uint amount, uint totalFee, uint reservesFee); uint constant flashFeeBips = 3; /** * @notice Initialize the new money market * @param underlying_ The address of the underlying asset * @param comptroller_ The address of the Comptroller * @param interestRateModel_ The address of the interest rate model * @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18 * @param name_ ERC-20 name of this token * @param symbol_ ERC-20 symbol of this token * @param decimals_ ERC-20 decimal precision of this token */ function initialize(address underlying_, ComptrollerInterface comptroller_, InterestRateModel interestRateModel_, uint initialExchangeRateMantissa_, string memory name_, string memory symbol_, uint8 decimals_) public { // CToken initialize does the bulk of the work super.initialize(comptroller_, interestRateModel_, initialExchangeRateMantissa_, name_, symbol_, decimals_); // Set underlying and sanity check it underlying = underlying_; EIP20Interface(underlying).totalSupply(); } /*** User Interface ***/ /** * @notice Sender supplies assets into the market and receives cTokens in exchange * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param mintAmount The amount of the underlying asset to supply * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function mint(uint mintAmount) external returns (uint) { (uint err,) = mintInternal(mintAmount); return err; } /** * @notice Sender redeems cTokens in exchange for the underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemTokens The number of cTokens to redeem into underlying * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeem(uint redeemTokens) external returns (uint) { return redeemInternal(redeemTokens); } /** * @notice Sender redeems cTokens in exchange for a specified amount of underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemAmount The amount of underlying to redeem * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemUnderlying(uint redeemAmount) external returns (uint) { return redeemUnderlyingInternal(redeemAmount); } /** * @notice Sender borrows assets from the protocol to their own address * @param borrowAmount The amount of the underlying asset to borrow * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrow(uint borrowAmount) external returns (uint) { return borrowInternal(borrowAmount); } /** * @notice Sender repays their own borrow * @param repayAmount The amount to repay * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function repayBorrow(uint repayAmount) external returns (uint) { (uint err,) = repayBorrowInternal(repayAmount); return err; } /** * @notice The sender liquidates the borrowers collateral. * The collateral seized is transferred to the liquidator. * @param borrower The borrower of this cToken to be liquidated * @param repayAmount The amount of the underlying borrowed asset to repay * @param cTokenCollateral The market in which to seize collateral from the borrower * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function liquidateBorrow(address borrower, uint repayAmount, CTokenInterface cTokenCollateral) external returns (uint) { (uint err,) = liquidateBorrowInternal(borrower, repayAmount, cTokenCollateral); return err; } /** * @notice The sender adds to reserves. * @param addAmount The amount fo underlying token to add as reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _addReserves(uint addAmount) external returns (uint) { return _addReservesInternal(addAmount); } /** * @notice Absorb excess cash into reserves. */ function gulp() external nonReentrant { uint256 cashOnChain = getCashOnChain(); uint256 cashPrior = getCashPrior(); uint excessCash = sub_(cashOnChain, cashPrior); totalReserves = add_(totalReserves, excessCash); internalCash = cashOnChain; } /*** Safe Token ***/ /** * @notice Gets internal balance of this contract in terms of the underlying. * It excludes balance from direct transfer. * @dev This excludes the value of the current message, if any * @return The quantity of underlying tokens owned by this contract */ function getCashPrior() internal view returns (uint) { return internalCash; } /** * @notice Gets total balance of this contract in terms of the underlying * @dev This excludes the value of the current message, if any * @return The quantity of underlying tokens owned by this contract */ function getCashOnChain() internal view returns (uint) { EIP20Interface token = EIP20Interface(underlying); return token.balanceOf(address(this)); } /** * @dev Similar to EIP20 transfer, except it handles a False result from `transferFrom` and reverts in that case. * This will revert due to insufficient balance or insufficient allowance. * This function returns the actual amount received, * which may be less than `amount` if there is a fee attached to the transfer. * * Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value. * See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */ function doTransferIn(address from, uint amount) internal returns (uint) { EIP20NonStandardInterface token = EIP20NonStandardInterface(underlying); uint balanceBefore = EIP20Interface(underlying).balanceOf(address(this)); token.transferFrom(from, address(this), amount); bool success; assembly { switch returndatasize() case 0 { // This is a non-standard ERC-20 success := not(0) // set success to true } case 32 { // This is a compliant ERC-20 returndatacopy(0, 0, 32) success := mload(0) // Set `success = returndata` of external call } default { // This is an excessively non-compliant ERC-20, revert. revert(0, 0) } } require(success, "TOKEN_TRANSFER_IN_FAILED"); // Calculate the amount that was *actually* transferred uint balanceAfter = EIP20Interface(underlying).balanceOf(address(this)); uint transferredIn = sub_(balanceAfter, balanceBefore); internalCash = add_(internalCash, transferredIn); return transferredIn; } /** * @dev Similar to EIP20 transfer, except it handles a False success from `transfer` and returns an explanatory * error code rather than reverting. If caller has not called checked protocol's balance, this may revert due to * insufficient cash held in this contract. If caller has checked protocol's balance prior to this call, and verified * it is >= amount, this should not revert in normal conditions. * * Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value. * See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */ function doTransferOut(address payable to, uint amount) internal { EIP20NonStandardInterface token = EIP20NonStandardInterface(underlying); token.transfer(to, amount); bool success; assembly { switch returndatasize() case 0 { // This is a non-standard ERC-20 success := not(0) // set success to true } case 32 { // This is a complaint ERC-20 returndatacopy(0, 0, 32) success := mload(0) // Set `success = returndata` of external call } default { // This is an excessively non-compliant ERC-20, revert. revert(0, 0) } } require(success, "TOKEN_TRANSFER_OUT_FAILED"); internalCash = sub_(internalCash, amount); } function flashLoan(address receiver, uint amount, bytes calldata params) external nonReentrant { uint cashOnChainBefore = getCashOnChain(); uint cashBefore = getCashPrior(); require(cashBefore >= amount, "INSUFFICIENT_LIQUIDITY"); // 1. calculate fee, 1 bips = 1/10000 uint totalFee = div_(mul_(amount, flashFeeBips), 10000); // 2. transfer fund to receiver doTransferOut(address(uint160(receiver)), amount); // 3. execute receiver's callback function IFlashloanReceiver(receiver).executeOperation(msg.sender, underlying, amount, totalFee, params); // 4. check balance uint cashOnChainAfter = getCashOnChain(); require(cashOnChainAfter == add_(cashOnChainBefore, totalFee), "BALANCE_INCONSISTENT"); // 5. update reserves and internal cash uint reservesFee = mul_ScalarTruncate(Exp({mantissa: reserveFactorMantissa}), totalFee); totalReserves = add_(totalReserves, reservesFee); internalCash = add_(cashBefore, totalFee); emit Flashloan(receiver, amount, totalFee, reservesFee); } } pragma solidity ^0.5.16; import "./CCapableErc20.sol"; /** * @title Compound's CCapableErc20Delegate Contract * @notice CTokens which wrap an EIP-20 underlying and are delegated to * @author Compound */ contract CCapableErc20Delegate is CCapableErc20 { /** * @notice Construct an empty delegate */ constructor() public {} /** * @notice Called by the delegator on a delegate to initialize it for duty * @param data The encoded bytes data for any initialization */ function _becomeImplementation(bytes memory data) public { // Shh -- currently unused data; // Shh -- we don't ever want this hook to be marked pure if (false) { implementation = address(0); } require(msg.sender == admin, "only the admin may call _becomeImplementation"); // Set internal cash when becoming implementation internalCash = getCashOnChain(); } /** * @notice Called by the delegator on a delegate to forfeit its responsibility */ function _resignImplementation() public { // Shh -- we don't ever want this hook to be marked pure if (false) { implementation = address(0); } require(msg.sender == admin, "only the admin may call _resignImplementation"); } } pragma solidity ^0.5.16; import "./ComptrollerInterface.sol"; import "./CTokenInterfaces.sol"; import "./ErrorReporter.sol"; import "./Exponential.sol"; import "./EIP20Interface.sol"; import "./EIP20NonStandardInterface.sol"; import "./InterestRateModel.sol"; /** * @title Compound's CToken Contract * @notice Abstract base for CTokens * @author Compound */ contract CToken is CTokenInterface, Exponential, TokenErrorReporter { /** * @notice Initialize the money market * @param comptroller_ The address of the Comptroller * @param interestRateModel_ The address of the interest rate model * @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18 * @param name_ EIP-20 name of this token * @param symbol_ EIP-20 symbol of this token * @param decimals_ EIP-20 decimal precision of this token */ function initialize(ComptrollerInterface comptroller_, InterestRateModel interestRateModel_, uint initialExchangeRateMantissa_, string memory name_, string memory symbol_, uint8 decimals_) public { require(msg.sender == admin, "only admin may initialize the market"); require(accrualBlockNumber == 0 && borrowIndex == 0, "market may only be initialized once"); // Set initial exchange rate initialExchangeRateMantissa = initialExchangeRateMantissa_; require(initialExchangeRateMantissa > 0, "initial exchange rate must be greater than zero."); // Set the comptroller uint err = _setComptroller(comptroller_); require(err == uint(Error.NO_ERROR), "setting comptroller failed"); // Initialize block number and borrow index (block number mocks depend on comptroller being set) accrualBlockNumber = getBlockNumber(); borrowIndex = mantissaOne; // Set the interest rate model (depends on block number / borrow index) err = _setInterestRateModelFresh(interestRateModel_); require(err == uint(Error.NO_ERROR), "setting interest rate model failed"); name = name_; symbol = symbol_; decimals = decimals_; // The counter starts true to prevent changing it from zero to non-zero (i.e. smaller cost/refund) _notEntered = true; } /** * @notice Transfer `tokens` tokens from `src` to `dst` by `spender` * @dev Called by both `transfer` and `transferFrom` internally * @param spender The address of the account performing the transfer * @param src The address of the source account * @param dst The address of the destination account * @param tokens The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferTokens(address spender, address src, address dst, uint tokens) internal returns (uint) { /* Fail if transfer not allowed */ uint allowed = comptroller.transferAllowed(address(this), src, dst, tokens); if (allowed != 0) { return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.TRANSFER_COMPTROLLER_REJECTION, allowed); } /* Do not allow self-transfers */ if (src == dst) { return fail(Error.BAD_INPUT, FailureInfo.TRANSFER_NOT_ALLOWED); } /* Get the allowance, infinite for the account owner */ uint startingAllowance = 0; if (spender == src) { startingAllowance = uint(-1); } else { startingAllowance = transferAllowances[src][spender]; } /* Do the calculations, checking for {under,over}flow */ uint allowanceNew = sub_(startingAllowance, tokens); uint srcTokensNew = sub_(accountTokens[src], tokens); uint dstTokensNew = add_(accountTokens[dst], tokens); ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) accountTokens[src] = srcTokensNew; accountTokens[dst] = dstTokensNew; /* Eat some of the allowance (if necessary) */ if (startingAllowance != uint(-1)) { transferAllowances[src][spender] = allowanceNew; } /* We emit a Transfer event */ emit Transfer(src, dst, tokens); comptroller.transferVerify(address(this), src, dst, tokens); return uint(Error.NO_ERROR); } /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint256 amount) external nonReentrant returns (bool) { return transferTokens(msg.sender, msg.sender, dst, amount) == uint(Error.NO_ERROR); } /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom(address src, address dst, uint256 amount) external nonReentrant returns (bool) { return transferTokens(msg.sender, src, dst, amount) == uint(Error.NO_ERROR); } /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved (-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint256 amount) external returns (bool) { address src = msg.sender; transferAllowances[src][spender] = amount; emit Approval(src, spender, amount); return true; } /** * @notice Get the current allowance from `owner` for `spender` * @param owner The address of the account which owns the tokens to be spent * @param spender The address of the account which may transfer tokens * @return The number of tokens allowed to be spent (-1 means infinite) */ function allowance(address owner, address spender) external view returns (uint256) { return transferAllowances[owner][spender]; } /** * @notice Get the token balance of the `owner` * @param owner The address of the account to query * @return The number of tokens owned by `owner` */ function balanceOf(address owner) external view returns (uint256) { return accountTokens[owner]; } /** * @notice Get the underlying balance of the `owner` * @dev This also accrues interest in a transaction * @param owner The address of the account to query * @return The amount of underlying owned by `owner` */ function balanceOfUnderlying(address owner) external returns (uint) { Exp memory exchangeRate = Exp({mantissa: exchangeRateCurrent()}); return mul_ScalarTruncate(exchangeRate, accountTokens[owner]); } /** * @notice Get a snapshot of the account's balances, and the cached exchange rate * @dev This is used by comptroller to more efficiently perform liquidity checks. * @param account Address of the account to snapshot * @return (possible error, token balance, borrow balance, exchange rate mantissa) */ function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint) { uint cTokenBalance = accountTokens[account]; uint borrowBalance = borrowBalanceStoredInternal(account); uint exchangeRateMantissa = exchangeRateStoredInternal(); return (uint(Error.NO_ERROR), cTokenBalance, borrowBalance, exchangeRateMantissa); } /** * @dev Function to simply retrieve block number * This exists mainly for inheriting test contracts to stub this result. */ function getBlockNumber() internal view returns (uint) { return block.number; } /** * @notice Returns the current per-block borrow interest rate for this cToken * @return The borrow interest rate per block, scaled by 1e18 */ function borrowRatePerBlock() external view returns (uint) { return interestRateModel.getBorrowRate(getCashPrior(), totalBorrows, totalReserves); } /** * @notice Returns the current per-block supply interest rate for this cToken * @return The supply interest rate per block, scaled by 1e18 */ function supplyRatePerBlock() external view returns (uint) { return interestRateModel.getSupplyRate(getCashPrior(), totalBorrows, totalReserves, reserveFactorMantissa); } /** * @notice Returns the current total borrows plus accrued interest * @return The total borrows with interest */ function totalBorrowsCurrent() external nonReentrant returns (uint) { require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed"); return totalBorrows; } /** * @notice Accrue interest to updated borrowIndex and then calculate account's borrow balance using the updated borrowIndex * @param account The address whose balance should be calculated after updating borrowIndex * @return The calculated balance */ function borrowBalanceCurrent(address account) external nonReentrant returns (uint) { require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed"); return borrowBalanceStored(account); } /** * @notice Return the borrow balance of account based on stored data * @param account The address whose balance should be calculated * @return The calculated balance */ function borrowBalanceStored(address account) public view returns (uint) { return borrowBalanceStoredInternal(account); } /** * @notice Return the borrow balance of account based on stored data * @param account The address whose balance should be calculated * @return the calculated balance or 0 if error code is non-zero */ function borrowBalanceStoredInternal(address account) internal view returns (uint) { /* Get borrowBalance and borrowIndex */ BorrowSnapshot storage borrowSnapshot = accountBorrows[account]; /* If borrowBalance = 0 then borrowIndex is likely also 0. * Rather than failing the calculation with a division by 0, we immediately return 0 in this case. */ if (borrowSnapshot.principal == 0) { return 0; } /* Calculate new borrow balance using the interest index: * recentBorrowBalance = borrower.borrowBalance * market.borrowIndex / borrower.borrowIndex */ uint principalTimesIndex = mul_(borrowSnapshot.principal, borrowIndex); uint result = div_(principalTimesIndex, borrowSnapshot.interestIndex); return result; } /** * @notice Accrue interest then return the up-to-date exchange rate * @return Calculated exchange rate scaled by 1e18 */ function exchangeRateCurrent() public nonReentrant returns (uint) { require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed"); return exchangeRateStored(); } /** * @notice Calculates the exchange rate from the underlying to the CToken * @dev This function does not accrue interest before calculating the exchange rate * @return Calculated exchange rate scaled by 1e18 */ function exchangeRateStored() public view returns (uint) { return exchangeRateStoredInternal(); } /** * @notice Calculates the exchange rate from the underlying to the CToken * @dev This function does not accrue interest before calculating the exchange rate * @return calculated exchange rate scaled by 1e18 */ function exchangeRateStoredInternal() internal view returns (uint) { uint _totalSupply = totalSupply; if (_totalSupply == 0) { /* * If there are no tokens minted: * exchangeRate = initialExchangeRate */ return initialExchangeRateMantissa; } else { /* * Otherwise: * exchangeRate = (totalCash + totalBorrows - totalReserves) / totalSupply */ uint totalCash = getCashPrior(); uint cashPlusBorrowsMinusReserves = sub_(add_(totalCash, totalBorrows), totalReserves); uint exchangeRate = div_(cashPlusBorrowsMinusReserves, Exp({mantissa: _totalSupply})); return exchangeRate; } } /** * @notice Get cash balance of this cToken in the underlying asset * @return The quantity of underlying asset owned by this contract */ function getCash() external view returns (uint) { return getCashPrior(); } /** * @notice Applies accrued interest to total borrows and reserves * @dev This calculates interest accrued from the last checkpointed block * up to the current block and writes new checkpoint to storage. */ function accrueInterest() public returns (uint) { /* Remember the initial block number */ uint currentBlockNumber = getBlockNumber(); uint accrualBlockNumberPrior = accrualBlockNumber; /* Short-circuit accumulating 0 interest */ if (accrualBlockNumberPrior == currentBlockNumber) { return uint(Error.NO_ERROR); } /* Read the previous values out of storage */ uint cashPrior = getCashPrior(); uint borrowsPrior = totalBorrows; uint reservesPrior = totalReserves; uint borrowIndexPrior = borrowIndex; /* Calculate the current borrow interest rate */ uint borrowRateMantissa = interestRateModel.getBorrowRate(cashPrior, borrowsPrior, reservesPrior); require(borrowRateMantissa <= borrowRateMaxMantissa, "borrow rate is absurdly high"); /* Calculate the number of blocks elapsed since the last accrual */ uint blockDelta = sub_(currentBlockNumber, accrualBlockNumberPrior); /* * Calculate the interest accumulated into borrows and reserves and the new index: * simpleInterestFactor = borrowRate * blockDelta * interestAccumulated = simpleInterestFactor * totalBorrows * totalBorrowsNew = interestAccumulated + totalBorrows * totalReservesNew = interestAccumulated * reserveFactor + totalReserves * borrowIndexNew = simpleInterestFactor * borrowIndex + borrowIndex */ Exp memory simpleInterestFactor = mul_(Exp({mantissa: borrowRateMantissa}), blockDelta); uint interestAccumulated = mul_ScalarTruncate(simpleInterestFactor, borrowsPrior); uint totalBorrowsNew = add_(interestAccumulated, borrowsPrior); uint totalReservesNew = mul_ScalarTruncateAddUInt(Exp({mantissa: reserveFactorMantissa}), interestAccumulated, reservesPrior); uint borrowIndexNew = mul_ScalarTruncateAddUInt(simpleInterestFactor, borrowIndexPrior, borrowIndexPrior); ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* We write the previously calculated values into storage */ accrualBlockNumber = currentBlockNumber; borrowIndex = borrowIndexNew; totalBorrows = totalBorrowsNew; totalReserves = totalReservesNew; /* We emit an AccrueInterest event */ emit AccrueInterest(cashPrior, interestAccumulated, borrowIndexNew, totalBorrowsNew); return uint(Error.NO_ERROR); } /** * @notice Sender supplies assets into the market and receives cTokens in exchange * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param mintAmount The amount of the underlying asset to supply * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount. */ function mintInternal(uint mintAmount) internal nonReentrant returns (uint, uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed return (fail(Error(error), FailureInfo.MINT_ACCRUE_INTEREST_FAILED), 0); } // mintFresh emits the actual Mint event if successful and logs on errors, so we don't need to return mintFresh(msg.sender, mintAmount); } struct MintLocalVars { Error err; MathError mathErr; uint exchangeRateMantissa; uint mintTokens; uint totalSupplyNew; uint accountTokensNew; uint actualMintAmount; } /** * @notice User supplies assets into the market and receives cTokens in exchange * @dev Assumes interest has already been accrued up to the current block * @param minter The address of the account which is supplying the assets * @param mintAmount The amount of the underlying asset to supply * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount. */ function mintFresh(address minter, uint mintAmount) internal returns (uint, uint) { /* Fail if mint not allowed */ uint allowed = comptroller.mintAllowed(address(this), minter, mintAmount); if (allowed != 0) { return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.MINT_COMPTROLLER_REJECTION, allowed), 0); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.MINT_FRESHNESS_CHECK), 0); } MintLocalVars memory vars; vars.exchangeRateMantissa = exchangeRateStoredInternal(); ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We call `doTransferIn` for the minter and the mintAmount. * Note: The cToken must handle variations between ERC-20 and ETH underlying. * `doTransferIn` reverts if anything goes wrong, since we can't be sure if * side-effects occurred. The function returns the amount actually transferred, * in case of a fee. On success, the cToken holds an additional `actualMintAmount` * of cash. */ vars.actualMintAmount = doTransferIn(minter, mintAmount); /* * We get the current exchange rate and calculate the number of cTokens to be minted: * mintTokens = actualMintAmount / exchangeRate */ vars.mintTokens = div_ScalarByExpTruncate(vars.actualMintAmount, Exp({mantissa: vars.exchangeRateMantissa})); /* * We calculate the new total supply of cTokens and minter token balance, checking for overflow: * totalSupplyNew = totalSupply + mintTokens * accountTokensNew = accountTokens[minter] + mintTokens */ vars.totalSupplyNew = add_(totalSupply, vars.mintTokens); vars.accountTokensNew = add_(accountTokens[minter], vars.mintTokens); /* We write previously calculated values into storage */ totalSupply = vars.totalSupplyNew; accountTokens[minter] = vars.accountTokensNew; /* We emit a Mint event, and a Transfer event */ emit Mint(minter, vars.actualMintAmount, vars.mintTokens); emit Transfer(address(this), minter, vars.mintTokens); /* We call the defense hook */ comptroller.mintVerify(address(this), minter, vars.actualMintAmount, vars.mintTokens); return (uint(Error.NO_ERROR), vars.actualMintAmount); } /** * @notice Sender redeems cTokens in exchange for the underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemTokens The number of cTokens to redeem into underlying * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemInternal(uint redeemTokens) internal nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED); } // redeemFresh emits redeem-specific logs on errors, so we don't need to return redeemFresh(msg.sender, redeemTokens, 0); } /** * @notice Sender redeems cTokens in exchange for a specified amount of underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemAmount The amount of underlying to receive from redeeming cTokens * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemUnderlyingInternal(uint redeemAmount) internal nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED); } // redeemFresh emits redeem-specific logs on errors, so we don't need to return redeemFresh(msg.sender, 0, redeemAmount); } struct RedeemLocalVars { Error err; MathError mathErr; uint exchangeRateMantissa; uint redeemTokens; uint redeemAmount; uint totalSupplyNew; uint accountTokensNew; } /** * @notice User redeems cTokens in exchange for the underlying asset * @dev Assumes interest has already been accrued up to the current block * @param redeemer The address of the account which is redeeming the tokens * @param redeemTokensIn The number of cTokens to redeem into underlying (only one of redeemTokensIn or redeemAmountIn may be non-zero) * @param redeemAmountIn The number of underlying tokens to receive from redeeming cTokens (only one of redeemTokensIn or redeemAmountIn may be non-zero) * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemFresh(address payable redeemer, uint redeemTokensIn, uint redeemAmountIn) internal returns (uint) { require(redeemTokensIn == 0 || redeemAmountIn == 0, "one of redeemTokensIn or redeemAmountIn must be zero"); RedeemLocalVars memory vars; /* exchangeRate = invoke Exchange Rate Stored() */ vars.exchangeRateMantissa = exchangeRateStoredInternal(); /* If redeemTokensIn > 0: */ if (redeemTokensIn > 0) { /* * We calculate the exchange rate and the amount of underlying to be redeemed: * redeemTokens = redeemTokensIn * redeemAmount = redeemTokensIn x exchangeRateCurrent */ vars.redeemTokens = redeemTokensIn; vars.redeemAmount = mul_ScalarTruncate(Exp({mantissa: vars.exchangeRateMantissa}), redeemTokensIn); } else { /* * We get the current exchange rate and calculate the amount to be redeemed: * redeemTokens = redeemAmountIn / exchangeRate * redeemAmount = redeemAmountIn */ vars.redeemTokens = div_ScalarByExpTruncate(redeemAmountIn, Exp({mantissa: vars.exchangeRateMantissa})); vars.redeemAmount = redeemAmountIn; } /* Fail if redeem not allowed */ uint allowed = comptroller.redeemAllowed(address(this), redeemer, vars.redeemTokens); if (allowed != 0) { return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.REDEEM_COMPTROLLER_REJECTION, allowed); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDEEM_FRESHNESS_CHECK); } /* * We calculate the new total supply and redeemer balance, checking for underflow: * totalSupplyNew = totalSupply - redeemTokens * accountTokensNew = accountTokens[redeemer] - redeemTokens */ vars.totalSupplyNew = sub_(totalSupply, vars.redeemTokens); vars.accountTokensNew = sub_(accountTokens[redeemer], vars.redeemTokens); /* Fail gracefully if protocol has insufficient cash */ if (getCashPrior() < vars.redeemAmount) { return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDEEM_TRANSFER_OUT_NOT_POSSIBLE); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We invoke doTransferOut for the redeemer and the redeemAmount. * Note: The cToken must handle variations between ERC-20 and ETH underlying. * On success, the cToken has redeemAmount less of cash. * doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred. */ doTransferOut(redeemer, vars.redeemAmount); /* We write previously calculated values into storage */ totalSupply = vars.totalSupplyNew; accountTokens[redeemer] = vars.accountTokensNew; /* We emit a Transfer event, and a Redeem event */ emit Transfer(redeemer, address(this), vars.redeemTokens); emit Redeem(redeemer, vars.redeemAmount, vars.redeemTokens); /* We call the defense hook */ comptroller.redeemVerify(address(this), redeemer, vars.redeemAmount, vars.redeemTokens); return uint(Error.NO_ERROR); } /** * @notice Sender borrows assets from the protocol to their own address * @param borrowAmount The amount of the underlying asset to borrow * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrowInternal(uint borrowAmount) internal nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed return fail(Error(error), FailureInfo.BORROW_ACCRUE_INTEREST_FAILED); } // borrowFresh emits borrow-specific logs on errors, so we don't need to return borrowFresh(msg.sender, borrowAmount); } struct BorrowLocalVars { MathError mathErr; uint accountBorrows; uint accountBorrowsNew; uint totalBorrowsNew; } /** * @notice Users borrow assets from the protocol to their own address * @param borrowAmount The amount of the underlying asset to borrow * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrowFresh(address payable borrower, uint borrowAmount) internal returns (uint) { /* Fail if borrow not allowed */ uint allowed = comptroller.borrowAllowed(address(this), borrower, borrowAmount); if (allowed != 0) { return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.BORROW_COMPTROLLER_REJECTION, allowed); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.BORROW_FRESHNESS_CHECK); } /* Fail gracefully if protocol has insufficient underlying cash */ if (getCashPrior() < borrowAmount) { return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.BORROW_CASH_NOT_AVAILABLE); } BorrowLocalVars memory vars; /* * We calculate the new borrower and total borrow balances, failing on overflow: * accountBorrowsNew = accountBorrows + borrowAmount * totalBorrowsNew = totalBorrows + borrowAmount */ vars.accountBorrows = borrowBalanceStoredInternal(borrower); vars.accountBorrowsNew = add_(vars.accountBorrows, borrowAmount); vars.totalBorrowsNew = add_(totalBorrows, borrowAmount); ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We invoke doTransferOut for the borrower and the borrowAmount. * Note: The cToken must handle variations between ERC-20 and ETH underlying. * On success, the cToken borrowAmount less of cash. * doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred. */ doTransferOut(borrower, borrowAmount); /* We write the previously calculated values into storage */ accountBorrows[borrower].principal = vars.accountBorrowsNew; accountBorrows[borrower].interestIndex = borrowIndex; totalBorrows = vars.totalBorrowsNew; /* We emit a Borrow event */ emit Borrow(borrower, borrowAmount, vars.accountBorrowsNew, vars.totalBorrowsNew); /* We call the defense hook */ comptroller.borrowVerify(address(this), borrower, borrowAmount); return uint(Error.NO_ERROR); } /** * @notice Sender repays their own borrow * @param repayAmount The amount to repay * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function repayBorrowInternal(uint repayAmount) internal nonReentrant returns (uint, uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed return (fail(Error(error), FailureInfo.REPAY_BORROW_ACCRUE_INTEREST_FAILED), 0); } // repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to return repayBorrowFresh(msg.sender, msg.sender, repayAmount); } struct RepayBorrowLocalVars { Error err; MathError mathErr; uint repayAmount; uint borrowerIndex; uint accountBorrows; uint accountBorrowsNew; uint totalBorrowsNew; uint actualRepayAmount; } /** * @notice Borrows are repaid by another user (possibly the borrower). * @param payer the account paying off the borrow * @param borrower the account with the debt being payed off * @param repayAmount the amount of undelrying tokens being returned * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function repayBorrowFresh(address payer, address borrower, uint repayAmount) internal returns (uint, uint) { /* Fail if repayBorrow not allowed */ uint allowed = comptroller.repayBorrowAllowed(address(this), payer, borrower, repayAmount); if (allowed != 0) { return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.REPAY_BORROW_COMPTROLLER_REJECTION, allowed), 0); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.REPAY_BORROW_FRESHNESS_CHECK), 0); } RepayBorrowLocalVars memory vars; /* We remember the original borrowerIndex for verification purposes */ vars.borrowerIndex = accountBorrows[borrower].interestIndex; /* We fetch the amount the borrower owes, with accumulated interest */ vars.accountBorrows = borrowBalanceStoredInternal(borrower); /* If repayAmount == -1, repayAmount = accountBorrows */ if (repayAmount == uint(-1)) { vars.repayAmount = vars.accountBorrows; } else { vars.repayAmount = repayAmount; } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We call doTransferIn for the payer and the repayAmount * Note: The cToken must handle variations between ERC-20 and ETH underlying. * On success, the cToken holds an additional repayAmount of cash. * doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred. * it returns the amount actually transferred, in case of a fee. */ vars.actualRepayAmount = doTransferIn(payer, vars.repayAmount); /* * We calculate the new borrower and total borrow balances, failing on underflow: * accountBorrowsNew = accountBorrows - actualRepayAmount * totalBorrowsNew = totalBorrows - actualRepayAmount */ vars.accountBorrowsNew = sub_(vars.accountBorrows, vars.actualRepayAmount); vars.totalBorrowsNew = sub_(totalBorrows, vars.actualRepayAmount); /* We write the previously calculated values into storage */ accountBorrows[borrower].principal = vars.accountBorrowsNew; accountBorrows[borrower].interestIndex = borrowIndex; totalBorrows = vars.totalBorrowsNew; /* We emit a RepayBorrow event */ emit RepayBorrow(payer, borrower, vars.actualRepayAmount, vars.accountBorrowsNew, vars.totalBorrowsNew); /* We call the defense hook */ comptroller.repayBorrowVerify(address(this), payer, borrower, vars.actualRepayAmount, vars.borrowerIndex); return (uint(Error.NO_ERROR), vars.actualRepayAmount); } /** * @notice The sender liquidates the borrowers collateral. * The collateral seized is transferred to the liquidator. * @param borrower The borrower of this cToken to be liquidated * @param cTokenCollateral The market in which to seize collateral from the borrower * @param repayAmount The amount of the underlying borrowed asset to repay * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function liquidateBorrowInternal(address borrower, uint repayAmount, CTokenInterface cTokenCollateral) internal nonReentrant returns (uint, uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED), 0); } error = cTokenCollateral.accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED), 0); } // liquidateBorrowFresh emits borrow-specific logs on errors, so we don't need to return liquidateBorrowFresh(msg.sender, borrower, repayAmount, cTokenCollateral); } /** * @notice The liquidator liquidates the borrowers collateral. * The collateral seized is transferred to the liquidator. * @param borrower The borrower of this cToken to be liquidated * @param liquidator The address repaying the borrow and seizing collateral * @param cTokenCollateral The market in which to seize collateral from the borrower * @param repayAmount The amount of the underlying borrowed asset to repay * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function liquidateBorrowFresh(address liquidator, address borrower, uint repayAmount, CTokenInterface cTokenCollateral) internal returns (uint, uint) { /* Fail if liquidate not allowed */ uint allowed = comptroller.liquidateBorrowAllowed(address(this), address(cTokenCollateral), liquidator, borrower, repayAmount); if (allowed != 0) { return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.LIQUIDATE_COMPTROLLER_REJECTION, allowed), 0); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_FRESHNESS_CHECK), 0); } /* Verify cTokenCollateral market's block number equals current block number */ if (cTokenCollateral.accrualBlockNumber() != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_COLLATERAL_FRESHNESS_CHECK), 0); } /* Fail if borrower = liquidator */ if (borrower == liquidator) { return (fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_LIQUIDATOR_IS_BORROWER), 0); } /* Fail if repayAmount = 0 */ if (repayAmount == 0) { return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_ZERO), 0); } /* Fail if repayAmount = -1 */ if (repayAmount == uint(-1)) { return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX), 0); } /* Fail if repayBorrow fails */ (uint repayBorrowError, uint actualRepayAmount) = repayBorrowFresh(liquidator, borrower, repayAmount); if (repayBorrowError != uint(Error.NO_ERROR)) { return (fail(Error(repayBorrowError), FailureInfo.LIQUIDATE_REPAY_BORROW_FRESH_FAILED), 0); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* We calculate the number of collateral tokens that will be seized */ (uint amountSeizeError, uint seizeTokens) = comptroller.liquidateCalculateSeizeTokens(address(this), address(cTokenCollateral), actualRepayAmount); require(amountSeizeError == uint(Error.NO_ERROR), "LIQUIDATE_COMPTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED"); /* Revert if borrower collateral token balance < seizeTokens */ require(cTokenCollateral.balanceOf(borrower) >= seizeTokens, "LIQUIDATE_SEIZE_TOO_MUCH"); // If this is also the collateral, run seizeInternal to avoid re-entrancy, otherwise make an external call uint seizeError; if (address(cTokenCollateral) == address(this)) { seizeError = seizeInternal(address(this), liquidator, borrower, seizeTokens); } else { seizeError = cTokenCollateral.seize(liquidator, borrower, seizeTokens); } /* Revert if seize tokens fails (since we cannot be sure of side effects) */ require(seizeError == uint(Error.NO_ERROR), "token seizure failed"); /* We emit a LiquidateBorrow event */ emit LiquidateBorrow(liquidator, borrower, actualRepayAmount, address(cTokenCollateral), seizeTokens); /* We call the defense hook */ comptroller.liquidateBorrowVerify(address(this), address(cTokenCollateral), liquidator, borrower, actualRepayAmount, seizeTokens); return (uint(Error.NO_ERROR), actualRepayAmount); } /** * @notice Transfers collateral tokens (this market) to the liquidator. * @dev Will fail unless called by another cToken during the process of liquidation. * Its absolutely critical to use msg.sender as the borrowed cToken and not a parameter. * @param liquidator The account receiving seized collateral * @param borrower The account having collateral seized * @param seizeTokens The number of cTokens to seize * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function seize(address liquidator, address borrower, uint seizeTokens) external nonReentrant returns (uint) { return seizeInternal(msg.sender, liquidator, borrower, seizeTokens); } /** * @notice Transfers collateral tokens (this market) to the liquidator. * @dev Called only during an in-kind liquidation, or by liquidateBorrow during the liquidation of another CToken. * Its absolutely critical to use msg.sender as the seizer cToken and not a parameter. * @param seizerToken The contract seizing the collateral (i.e. borrowed cToken) * @param liquidator The account receiving seized collateral * @param borrower The account having collateral seized * @param seizeTokens The number of cTokens to seize * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function seizeInternal(address seizerToken, address liquidator, address borrower, uint seizeTokens) internal returns (uint) { /* Fail if seize not allowed */ uint allowed = comptroller.seizeAllowed(address(this), seizerToken, liquidator, borrower, seizeTokens); if (allowed != 0) { return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.LIQUIDATE_SEIZE_COMPTROLLER_REJECTION, allowed); } /* Fail if borrower = liquidator */ if (borrower == liquidator) { return fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER); } /* * We calculate the new borrower and liquidator token balances, failing on underflow/overflow: * borrowerTokensNew = accountTokens[borrower] - seizeTokens * liquidatorTokensNew = accountTokens[liquidator] + seizeTokens */ uint borrowerTokensNew = sub_(accountTokens[borrower], seizeTokens); uint liquidatorTokensNew = add_(accountTokens[liquidator], seizeTokens); ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* We write the previously calculated values into storage */ accountTokens[borrower] = borrowerTokensNew; accountTokens[liquidator] = liquidatorTokensNew; /* Emit a Transfer event */ emit Transfer(borrower, liquidator, seizeTokens); /* We call the defense hook */ comptroller.seizeVerify(address(this), seizerToken, liquidator, borrower, seizeTokens); return uint(Error.NO_ERROR); } /*** Admin Functions ***/ /** * @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @param newPendingAdmin New pending admin. * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setPendingAdmin(address payable newPendingAdmin) external returns (uint) { // Check caller = admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK); } // Save current value, if any, for inclusion in log address oldPendingAdmin = pendingAdmin; // Store pendingAdmin with value newPendingAdmin pendingAdmin = newPendingAdmin; // Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin) emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin); return uint(Error.NO_ERROR); } /** * @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin * @dev Admin function for pending admin to accept role and update admin * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _acceptAdmin() external returns (uint) { // Check caller is pendingAdmin and pendingAdmin ≠ address(0) if (msg.sender != pendingAdmin || msg.sender == address(0)) { return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_ADMIN_PENDING_ADMIN_CHECK); } // Save current values for inclusion in log address oldAdmin = admin; address oldPendingAdmin = pendingAdmin; // Store admin with value pendingAdmin admin = pendingAdmin; // Clear the pending value pendingAdmin = address(0); emit NewAdmin(oldAdmin, admin); emit NewPendingAdmin(oldPendingAdmin, pendingAdmin); return uint(Error.NO_ERROR); } /** * @notice Sets a new comptroller for the market * @dev Admin function to set a new comptroller * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setComptroller(ComptrollerInterface newComptroller) public returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_COMPTROLLER_OWNER_CHECK); } ComptrollerInterface oldComptroller = comptroller; // Ensure invoke comptroller.isComptroller() returns true require(newComptroller.isComptroller(), "marker method returned false"); // Set market's comptroller to newComptroller comptroller = newComptroller; // Emit NewComptroller(oldComptroller, newComptroller) emit NewComptroller(oldComptroller, newComptroller); return uint(Error.NO_ERROR); } /** * @notice accrues interest and sets a new reserve factor for the protocol using _setReserveFactorFresh * @dev Admin function to accrue interest and set a new reserve factor * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setReserveFactor(uint newReserveFactorMantissa) external nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reserve factor change failed. return fail(Error(error), FailureInfo.SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED); } // _setReserveFactorFresh emits reserve-factor-specific logs on errors, so we don't need to. return _setReserveFactorFresh(newReserveFactorMantissa); } /** * @notice Sets a new reserve factor for the protocol (*requires fresh interest accrual) * @dev Admin function to set a new reserve factor * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setReserveFactorFresh(uint newReserveFactorMantissa) internal returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_RESERVE_FACTOR_ADMIN_CHECK); } // Verify market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_RESERVE_FACTOR_FRESH_CHECK); } // Check newReserveFactor ≤ maxReserveFactor if (newReserveFactorMantissa > reserveFactorMaxMantissa) { return fail(Error.BAD_INPUT, FailureInfo.SET_RESERVE_FACTOR_BOUNDS_CHECK); } uint oldReserveFactorMantissa = reserveFactorMantissa; reserveFactorMantissa = newReserveFactorMantissa; emit NewReserveFactor(oldReserveFactorMantissa, newReserveFactorMantissa); return uint(Error.NO_ERROR); } /** * @notice Accrues interest and reduces reserves by transferring from msg.sender * @param addAmount Amount of addition to reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _addReservesInternal(uint addAmount) internal nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed. return fail(Error(error), FailureInfo.ADD_RESERVES_ACCRUE_INTEREST_FAILED); } // _addReservesFresh emits reserve-addition-specific logs on errors, so we don't need to. (error, ) = _addReservesFresh(addAmount); return error; } /** * @notice Add reserves by transferring from caller * @dev Requires fresh interest accrual * @param addAmount Amount of addition to reserves * @return (uint, uint) An error code (0=success, otherwise a failure (see ErrorReporter.sol for details)) and the actual amount added, net token fees */ function _addReservesFresh(uint addAmount) internal returns (uint, uint) { // totalReserves + actualAddAmount uint totalReservesNew; uint actualAddAmount; // We fail gracefully unless market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.ADD_RESERVES_FRESH_CHECK), actualAddAmount); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We call doTransferIn for the caller and the addAmount * Note: The cToken must handle variations between ERC-20 and ETH underlying. * On success, the cToken holds an additional addAmount of cash. * doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred. * it returns the amount actually transferred, in case of a fee. */ actualAddAmount = doTransferIn(msg.sender, addAmount); totalReservesNew = add_(totalReserves, actualAddAmount); // Store reserves[n+1] = reserves[n] + actualAddAmount totalReserves = totalReservesNew; /* Emit NewReserves(admin, actualAddAmount, reserves[n+1]) */ emit ReservesAdded(msg.sender, actualAddAmount, totalReservesNew); /* Return (NO_ERROR, actualAddAmount) */ return (uint(Error.NO_ERROR), actualAddAmount); } /** * @notice Accrues interest and reduces reserves by transferring to admin * @param reduceAmount Amount of reduction to reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _reduceReserves(uint reduceAmount) external nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed. return fail(Error(error), FailureInfo.REDUCE_RESERVES_ACCRUE_INTEREST_FAILED); } // _reduceReservesFresh emits reserve-reduction-specific logs on errors, so we don't need to. return _reduceReservesFresh(reduceAmount); } /** * @notice Reduces reserves by transferring to admin * @dev Requires fresh interest accrual * @param reduceAmount Amount of reduction to reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _reduceReservesFresh(uint reduceAmount) internal returns (uint) { // totalReserves - reduceAmount uint totalReservesNew; // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.REDUCE_RESERVES_ADMIN_CHECK); } // We fail gracefully unless market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDUCE_RESERVES_FRESH_CHECK); } // Fail gracefully if protocol has insufficient underlying cash if (getCashPrior() < reduceAmount) { return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDUCE_RESERVES_CASH_NOT_AVAILABLE); } // Check reduceAmount ≤ reserves[n] (totalReserves) if (reduceAmount > totalReserves) { return fail(Error.BAD_INPUT, FailureInfo.REDUCE_RESERVES_VALIDATION); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) totalReservesNew = sub_(totalReserves, reduceAmount); // Store reserves[n+1] = reserves[n] - reduceAmount totalReserves = totalReservesNew; // doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred. doTransferOut(admin, reduceAmount); emit ReservesReduced(admin, reduceAmount, totalReservesNew); return uint(Error.NO_ERROR); } /** * @notice accrues interest and updates the interest rate model using _setInterestRateModelFresh * @dev Admin function to accrue interest and update the interest rate model * @param newInterestRateModel the new interest rate model to use * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted change of interest rate model failed return fail(Error(error), FailureInfo.SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED); } // _setInterestRateModelFresh emits interest-rate-model-update-specific logs on errors, so we don't need to. return _setInterestRateModelFresh(newInterestRateModel); } /** * @notice updates the interest rate model (*requires fresh interest accrual) * @dev Admin function to update the interest rate model * @param newInterestRateModel the new interest rate model to use * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setInterestRateModelFresh(InterestRateModel newInterestRateModel) internal returns (uint) { // Used to store old model for use in the event that is emitted on success InterestRateModel oldInterestRateModel; // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_INTEREST_RATE_MODEL_OWNER_CHECK); } // We fail gracefully unless market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_INTEREST_RATE_MODEL_FRESH_CHECK); } // Track the market's current interest rate model oldInterestRateModel = interestRateModel; // Ensure invoke newInterestRateModel.isInterestRateModel() returns true require(newInterestRateModel.isInterestRateModel(), "marker method returned false"); // Set the interest rate model to newInterestRateModel interestRateModel = newInterestRateModel; // Emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel) emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel); return uint(Error.NO_ERROR); } /*** Safe Token ***/ /** * @notice Gets balance of this contract in terms of the underlying * @dev This excludes the value of the current message, if any * @return The quantity of underlying owned by this contract */ function getCashPrior() internal view returns (uint); /** * @dev Performs a transfer in, reverting upon failure. Returns the amount actually transferred to the protocol, in case of a fee. * This may revert due to insufficient balance or insufficient allowance. */ function doTransferIn(address from, uint amount) internal returns (uint); /** * @dev Performs a transfer out, ideally returning an explanatory error code upon failure tather than reverting. * If caller has not called checked protocol's balance, may revert due to insufficient cash held in the contract. * If caller has checked protocol's balance, and verified it is >= amount, this should not revert in normal conditions. */ function doTransferOut(address payable to, uint amount) internal; /*** Reentrancy Guard ***/ /** * @dev Prevents a contract from calling itself, directly or indirectly. */ modifier nonReentrant() { require(_notEntered, "re-entered"); _notEntered = false; _; _notEntered = true; // get a gas-refund post-Istanbul } } pragma solidity ^0.5.16; import "./ComptrollerInterface.sol"; import "./InterestRateModel.sol"; contract CTokenStorage { /** * @dev Guard variable for re-entrancy checks */ bool internal _notEntered; /** * @notice EIP-20 token name for this token */ string public name; /** * @notice EIP-20 token symbol for this token */ string public symbol; /** * @notice EIP-20 token decimals for this token */ uint8 public decimals; /** * @notice Maximum borrow rate that can ever be applied (.0005% / block) */ uint internal constant borrowRateMaxMantissa = 0.0005e16; /** * @notice Maximum fraction of interest that can be set aside for reserves */ uint internal constant reserveFactorMaxMantissa = 1e18; /** * @notice Administrator for this contract */ address payable public admin; /** * @notice Pending administrator for this contract */ address payable public pendingAdmin; /** * @notice Contract which oversees inter-cToken operations */ ComptrollerInterface public comptroller; /** * @notice Model which tells what the current interest rate should be */ InterestRateModel public interestRateModel; /** * @notice Initial exchange rate used when minting the first CTokens (used when totalSupply = 0) */ uint internal initialExchangeRateMantissa; /** * @notice Fraction of interest currently set aside for reserves */ uint public reserveFactorMantissa; /** * @notice Block number that interest was last accrued at */ uint public accrualBlockNumber; /** * @notice Accumulator of the total earned interest rate since the opening of the market */ uint public borrowIndex; /** * @notice Total amount of outstanding borrows of the underlying in this market */ uint public totalBorrows; /** * @notice Total amount of reserves of the underlying held in this market */ uint public totalReserves; /** * @notice Total number of tokens in circulation */ uint public totalSupply; /** * @notice Official record of token balances for each account */ mapping (address => uint) internal accountTokens; /** * @notice Approved token transfer amounts on behalf of others */ mapping (address => mapping (address => uint)) internal transferAllowances; /** * @notice Container for borrow balance information * @member principal Total balance (with accrued interest), after applying the most recent balance-changing action * @member interestIndex Global borrowIndex as of the most recent balance-changing action */ struct BorrowSnapshot { uint principal; uint interestIndex; } /** * @notice Mapping of account addresses to outstanding borrow balances */ mapping(address => BorrowSnapshot) internal accountBorrows; } contract CTokenInterface is CTokenStorage { /** * @notice Indicator that this is a CToken contract (for inspection) */ bool public constant isCToken = true; /*** Market Events ***/ /** * @notice Event emitted when interest is accrued */ event AccrueInterest(uint cashPrior, uint interestAccumulated, uint borrowIndex, uint totalBorrows); /** * @notice Event emitted when tokens are minted */ event Mint(address minter, uint mintAmount, uint mintTokens); /** * @notice Event emitted when tokens are redeemed */ event Redeem(address redeemer, uint redeemAmount, uint redeemTokens); /** * @notice Event emitted when underlying is borrowed */ event Borrow(address borrower, uint borrowAmount, uint accountBorrows, uint totalBorrows); /** * @notice Event emitted when a borrow is repaid */ event RepayBorrow(address payer, address borrower, uint repayAmount, uint accountBorrows, uint totalBorrows); /** * @notice Event emitted when a borrow is liquidated */ event LiquidateBorrow(address liquidator, address borrower, uint repayAmount, address cTokenCollateral, uint seizeTokens); /*** Admin Events ***/ /** * @notice Event emitted when pendingAdmin is changed */ event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin); /** * @notice Event emitted when pendingAdmin is accepted, which means admin is updated */ event NewAdmin(address oldAdmin, address newAdmin); /** * @notice Event emitted when comptroller is changed */ event NewComptroller(ComptrollerInterface oldComptroller, ComptrollerInterface newComptroller); /** * @notice Event emitted when interestRateModel is changed */ event NewMarketInterestRateModel(InterestRateModel oldInterestRateModel, InterestRateModel newInterestRateModel); /** * @notice Event emitted when the reserve factor is changed */ event NewReserveFactor(uint oldReserveFactorMantissa, uint newReserveFactorMantissa); /** * @notice Event emitted when the reserves are added */ event ReservesAdded(address benefactor, uint addAmount, uint newTotalReserves); /** * @notice Event emitted when the reserves are reduced */ event ReservesReduced(address admin, uint reduceAmount, uint newTotalReserves); /** * @notice EIP20 Transfer event */ event Transfer(address indexed from, address indexed to, uint amount); /** * @notice EIP20 Approval event */ event Approval(address indexed owner, address indexed spender, uint amount); /** * @notice Failure event */ event Failure(uint error, uint info, uint detail); /*** User Interface ***/ function transfer(address dst, uint amount) external returns (bool); function transferFrom(address src, address dst, uint amount) external returns (bool); function approve(address spender, uint amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint); function balanceOf(address owner) external view returns (uint); function balanceOfUnderlying(address owner) external returns (uint); function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint); function borrowRatePerBlock() external view returns (uint); function supplyRatePerBlock() external view returns (uint); function totalBorrowsCurrent() external returns (uint); function borrowBalanceCurrent(address account) external returns (uint); function borrowBalanceStored(address account) public view returns (uint); function exchangeRateCurrent() public returns (uint); function exchangeRateStored() public view returns (uint); function getCash() external view returns (uint); function accrueInterest() public returns (uint); function seize(address liquidator, address borrower, uint seizeTokens) external returns (uint); /*** Admin Functions ***/ function _setPendingAdmin(address payable newPendingAdmin) external returns (uint); function _acceptAdmin() external returns (uint); function _setComptroller(ComptrollerInterface newComptroller) public returns (uint); function _setReserveFactor(uint newReserveFactorMantissa) external returns (uint); function _reduceReserves(uint reduceAmount) external returns (uint); function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint); } contract CErc20Storage { /** * @notice Underlying asset for this CToken */ address public underlying; } contract CErc20Interface is CErc20Storage { /*** User Interface ***/ function mint(uint mintAmount) external returns (uint); function redeem(uint redeemTokens) external returns (uint); function redeemUnderlying(uint redeemAmount) external returns (uint); function borrow(uint borrowAmount) external returns (uint); function repayBorrow(uint repayAmount) external returns (uint); function liquidateBorrow(address borrower, uint repayAmount, CTokenInterface cTokenCollateral) external returns (uint); /*** Admin Functions ***/ function _addReserves(uint addAmount) external returns (uint); } contract CCapableErc20Interface is CErc20Storage { /*** User Interface ***/ function mint(uint mintAmount) external returns (uint); function redeem(uint redeemTokens) external returns (uint); function redeemUnderlying(uint redeemAmount) external returns (uint); function borrow(uint borrowAmount) external returns (uint); function repayBorrow(uint repayAmount) external returns (uint); function liquidateBorrow(address borrower, uint repayAmount, CTokenInterface cTokenCollateral) external returns (uint); function gulp() external; /*** Admin Functions ***/ function _addReserves(uint addAmount) external returns (uint); } contract CDelegationStorage { /** * @notice Implementation address for this contract */ address public implementation; } contract CDelegationStorageExtension is CDelegationStorage { /** * @notice Internal cash counter for this CToken. Should equal underlying.balanceOf(address(this)) for CERC20. */ uint256 public internalCash; } contract CDelegatorInterface is CDelegationStorage { /** * @notice Emitted when implementation is changed */ event NewImplementation(address oldImplementation, address newImplementation); /** * @notice Called by the admin to update the implementation of the delegator * @param implementation_ The address of the new implementation for delegation * @param allowResign Flag to indicate whether to call _resignImplementation on the old implementation * @param becomeImplementationData The encoded bytes data to be passed to _becomeImplementation */ function _setImplementation(address implementation_, bool allowResign, bytes memory becomeImplementationData) public; } contract CDelegateInterface is CDelegationStorage { /** * @notice Called by the delegator on a delegate to initialize it for duty * @dev Should revert if any issues arise which make it unfit for delegation * @param data The encoded bytes data for any initialization */ function _becomeImplementation(bytes memory data) public; /** * @notice Called by the delegator on a delegate to forfeit its responsibility */ function _resignImplementation() public; } contract CCapableDelegateInterface is CDelegationStorageExtension { /** * @notice Called by the delegator on a delegate to initialize it for duty * @dev Should revert if any issues arise which make it unfit for delegation * @param data The encoded bytes data for any initialization */ function _becomeImplementation(bytes memory data) public; /** * @notice Called by the delegator on a delegate to forfeit its responsibility */ function _resignImplementation() public; } pragma solidity ^0.5.16; /** * @title Careful Math * @author Compound * @notice Derived from OpenZeppelin's SafeMath library * https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/math/SafeMath.sol */ contract CarefulMath { /** * @dev Possible error codes that we can return */ enum MathError { NO_ERROR, DIVISION_BY_ZERO, INTEGER_OVERFLOW, INTEGER_UNDERFLOW } /** * @dev Multiplies two numbers, returns an error on overflow. */ function mulUInt(uint a, uint b) internal pure returns (MathError, uint) { if (a == 0) { return (MathError.NO_ERROR, 0); } uint c = a * b; if (c / a != b) { return (MathError.INTEGER_OVERFLOW, 0); } else { return (MathError.NO_ERROR, c); } } /** * @dev Integer division of two numbers, truncating the quotient. */ function divUInt(uint a, uint b) internal pure returns (MathError, uint) { if (b == 0) { return (MathError.DIVISION_BY_ZERO, 0); } return (MathError.NO_ERROR, a / b); } /** * @dev Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend). */ function subUInt(uint a, uint b) internal pure returns (MathError, uint) { if (b <= a) { return (MathError.NO_ERROR, a - b); } else { return (MathError.INTEGER_UNDERFLOW, 0); } } /** * @dev Adds two numbers, returns an error on overflow. */ function addUInt(uint a, uint b) internal pure returns (MathError, uint) { uint c = a + b; if (c >= a) { return (MathError.NO_ERROR, c); } else { return (MathError.INTEGER_OVERFLOW, 0); } } /** * @dev add a and b and then subtract c */ function addThenSubUInt(uint a, uint b, uint c) internal pure returns (MathError, uint) { (MathError err0, uint sum) = addUInt(a, b); if (err0 != MathError.NO_ERROR) { return (err0, 0); } return subUInt(sum, c); } } pragma solidity ^0.5.16; contract ComptrollerInterface { /// @notice Indicator that this is a Comptroller contract (for inspection) bool public constant isComptroller = true; /*** Assets You Are In ***/ function enterMarkets(address[] calldata cTokens) external returns (uint[] memory); function exitMarket(address cToken) external returns (uint); /*** Policy Hooks ***/ function mintAllowed(address cToken, address minter, uint mintAmount) external returns (uint); function mintVerify(address cToken, address minter, uint mintAmount, uint mintTokens) external; function redeemAllowed(address cToken, address redeemer, uint redeemTokens) external returns (uint); function redeemVerify(address cToken, address redeemer, uint redeemAmount, uint redeemTokens) external; function borrowAllowed(address cToken, address borrower, uint borrowAmount) external returns (uint); function borrowVerify(address cToken, address borrower, uint borrowAmount) external; function repayBorrowAllowed( address cToken, address payer, address borrower, uint repayAmount) external returns (uint); function repayBorrowVerify( address cToken, address payer, address borrower, uint repayAmount, uint borrowerIndex) external; function liquidateBorrowAllowed( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint repayAmount) external returns (uint); function liquidateBorrowVerify( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint repayAmount, uint seizeTokens) external; function seizeAllowed( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint seizeTokens) external returns (uint); function seizeVerify( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint seizeTokens) external; function transferAllowed(address cToken, address src, address dst, uint transferTokens) external returns (uint); function transferVerify(address cToken, address src, address dst, uint transferTokens) external; /*** Liquidity/Liquidation Calculations ***/ function liquidateCalculateSeizeTokens( address cTokenBorrowed, address cTokenCollateral, uint repayAmount) external view returns (uint, uint); } pragma solidity ^0.5.16; /** * @title ERC 20 Token Standard Interface * https://eips.ethereum.org/EIPS/eip-20 */ interface EIP20Interface { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); /** * @notice Get the total number of tokens in circulation * @return The supply of tokens */ function totalSupply() external view returns (uint256); /** * @notice Gets the balance of the specified address * @param owner The address from which the balance will be retrieved * @return The balance */ function balanceOf(address owner) external view returns (uint256 balance); /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint256 amount) external returns (bool success); /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom(address src, address dst, uint256 amount) external returns (bool success); /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved (-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint256 amount) external returns (bool success); /** * @notice Get the current allowance from `owner` for `spender` * @param owner The address of the account which owns the tokens to be spent * @param spender The address of the account which may transfer tokens * @return The number of tokens allowed to be spent (-1 means infinite) */ function allowance(address owner, address spender) external view returns (uint256 remaining); event Transfer(address indexed from, address indexed to, uint256 amount); event Approval(address indexed owner, address indexed spender, uint256 amount); } pragma solidity ^0.5.16; /** * @title EIP20NonStandardInterface * @dev Version of ERC20 with no return values for `transfer` and `transferFrom` * See https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */ interface EIP20NonStandardInterface { /** * @notice Get the total number of tokens in circulation * @return The supply of tokens */ function totalSupply() external view returns (uint256); /** * @notice Gets the balance of the specified address * @param owner The address from which the balance will be retrieved * @return The balance */ function balanceOf(address owner) external view returns (uint256 balance); /// /// !!!!!!!!!!!!!! /// !!! NOTICE !!! `transfer` does not return a value, in violation of the ERC-20 specification /// !!!!!!!!!!!!!! /// /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer */ function transfer(address dst, uint256 amount) external; /// /// !!!!!!!!!!!!!! /// !!! NOTICE !!! `transferFrom` does not return a value, in violation of the ERC-20 specification /// !!!!!!!!!!!!!! /// /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer */ function transferFrom(address src, address dst, uint256 amount) external; /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved * @return Whether or not the approval succeeded */ function approve(address spender, uint256 amount) external returns (bool success); /** * @notice Get the current allowance from `owner` for `spender` * @param owner The address of the account which owns the tokens to be spent * @param spender The address of the account which may transfer tokens * @return The number of tokens allowed to be spent */ function allowance(address owner, address spender) external view returns (uint256 remaining); event Transfer(address indexed from, address indexed to, uint256 amount); event Approval(address indexed owner, address indexed spender, uint256 amount); } pragma solidity ^0.5.16; contract ComptrollerErrorReporter { enum Error { NO_ERROR, UNAUTHORIZED, COMPTROLLER_MISMATCH, INSUFFICIENT_SHORTFALL, INSUFFICIENT_LIQUIDITY, INVALID_CLOSE_FACTOR, INVALID_COLLATERAL_FACTOR, INVALID_LIQUIDATION_INCENTIVE, MARKET_NOT_ENTERED, // no longer possible MARKET_NOT_LISTED, MARKET_ALREADY_LISTED, MATH_ERROR, NONZERO_BORROW_BALANCE, PRICE_ERROR, REJECTION, SNAPSHOT_ERROR, TOO_MANY_ASSETS, TOO_MUCH_REPAY } enum FailureInfo { ACCEPT_ADMIN_PENDING_ADMIN_CHECK, ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK, EXIT_MARKET_BALANCE_OWED, EXIT_MARKET_REJECTION, SET_CLOSE_FACTOR_OWNER_CHECK, SET_CLOSE_FACTOR_VALIDATION, SET_COLLATERAL_FACTOR_OWNER_CHECK, SET_COLLATERAL_FACTOR_NO_EXISTS, SET_COLLATERAL_FACTOR_VALIDATION, SET_COLLATERAL_FACTOR_WITHOUT_PRICE, SET_IMPLEMENTATION_OWNER_CHECK, SET_LIQUIDATION_INCENTIVE_OWNER_CHECK, SET_LIQUIDATION_INCENTIVE_VALIDATION, SET_MAX_ASSETS_OWNER_CHECK, SET_PENDING_ADMIN_OWNER_CHECK, SET_PENDING_IMPLEMENTATION_OWNER_CHECK, SET_PRICE_ORACLE_OWNER_CHECK, SUPPORT_MARKET_EXISTS, SUPPORT_MARKET_OWNER_CHECK, SET_PAUSE_GUARDIAN_OWNER_CHECK } /** * @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary * contract-specific code that enables us to report opaque error codes from upgradeable contracts. **/ event Failure(uint error, uint info, uint detail); /** * @dev use this when reporting a known error from the money market or a non-upgradeable collaborator */ function fail(Error err, FailureInfo info) internal returns (uint) { emit Failure(uint(err), uint(info), 0); return uint(err); } /** * @dev use this when reporting an opaque error from an upgradeable collaborator contract */ function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) { emit Failure(uint(err), uint(info), opaqueError); return uint(err); } } contract TokenErrorReporter { enum Error { NO_ERROR, UNAUTHORIZED, BAD_INPUT, COMPTROLLER_REJECTION, COMPTROLLER_CALCULATION_ERROR, INTEREST_RATE_MODEL_ERROR, INVALID_ACCOUNT_PAIR, INVALID_CLOSE_AMOUNT_REQUESTED, INVALID_COLLATERAL_FACTOR, MATH_ERROR, MARKET_NOT_FRESH, MARKET_NOT_LISTED, TOKEN_INSUFFICIENT_ALLOWANCE, TOKEN_INSUFFICIENT_BALANCE, TOKEN_INSUFFICIENT_CASH, TOKEN_TRANSFER_IN_FAILED, TOKEN_TRANSFER_OUT_FAILED } /* * Note: FailureInfo (but not Error) is kept in alphabetical order * This is because FailureInfo grows significantly faster, and * the order of Error has some meaning, while the order of FailureInfo * is entirely arbitrary. */ enum FailureInfo { ACCEPT_ADMIN_PENDING_ADMIN_CHECK, ACCRUE_INTEREST_BORROW_RATE_CALCULATION_FAILED, BORROW_ACCRUE_INTEREST_FAILED, BORROW_CASH_NOT_AVAILABLE, BORROW_FRESHNESS_CHECK, BORROW_MARKET_NOT_LISTED, BORROW_COMPTROLLER_REJECTION, LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED, LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED, LIQUIDATE_COLLATERAL_FRESHNESS_CHECK, LIQUIDATE_COMPTROLLER_REJECTION, LIQUIDATE_COMPTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED, LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX, LIQUIDATE_CLOSE_AMOUNT_IS_ZERO, LIQUIDATE_FRESHNESS_CHECK, LIQUIDATE_LIQUIDATOR_IS_BORROWER, LIQUIDATE_REPAY_BORROW_FRESH_FAILED, LIQUIDATE_SEIZE_COMPTROLLER_REJECTION, LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER, LIQUIDATE_SEIZE_TOO_MUCH, MINT_ACCRUE_INTEREST_FAILED, MINT_COMPTROLLER_REJECTION, MINT_FRESHNESS_CHECK, MINT_TRANSFER_IN_FAILED, MINT_TRANSFER_IN_NOT_POSSIBLE, REDEEM_ACCRUE_INTEREST_FAILED, REDEEM_COMPTROLLER_REJECTION, REDEEM_FRESHNESS_CHECK, REDEEM_TRANSFER_OUT_NOT_POSSIBLE, REDUCE_RESERVES_ACCRUE_INTEREST_FAILED, REDUCE_RESERVES_ADMIN_CHECK, REDUCE_RESERVES_CASH_NOT_AVAILABLE, REDUCE_RESERVES_FRESH_CHECK, REDUCE_RESERVES_VALIDATION, REPAY_BORROW_ACCRUE_INTEREST_FAILED, REPAY_BORROW_COMPTROLLER_REJECTION, REPAY_BORROW_FRESHNESS_CHECK, REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE, SET_COLLATERAL_FACTOR_OWNER_CHECK, SET_COLLATERAL_FACTOR_VALIDATION, SET_COMPTROLLER_OWNER_CHECK, SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED, SET_INTEREST_RATE_MODEL_FRESH_CHECK, SET_INTEREST_RATE_MODEL_OWNER_CHECK, SET_MAX_ASSETS_OWNER_CHECK, SET_ORACLE_MARKET_NOT_LISTED, SET_PENDING_ADMIN_OWNER_CHECK, SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED, SET_RESERVE_FACTOR_ADMIN_CHECK, SET_RESERVE_FACTOR_FRESH_CHECK, SET_RESERVE_FACTOR_BOUNDS_CHECK, TRANSFER_COMPTROLLER_REJECTION, TRANSFER_NOT_ALLOWED, ADD_RESERVES_ACCRUE_INTEREST_FAILED, ADD_RESERVES_FRESH_CHECK, ADD_RESERVES_TRANSFER_IN_NOT_POSSIBLE } /** * @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary * contract-specific code that enables us to report opaque error codes from upgradeable contracts. **/ event Failure(uint error, uint info, uint detail); /** * @dev use this when reporting a known error from the money market or a non-upgradeable collaborator */ function fail(Error err, FailureInfo info) internal returns (uint) { emit Failure(uint(err), uint(info), 0); return uint(err); } /** * @dev use this when reporting an opaque error from an upgradeable collaborator contract */ function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) { emit Failure(uint(err), uint(info), opaqueError); return uint(err); } } pragma solidity ^0.5.16; import "./CarefulMath.sol"; /** * @title Exponential module for storing fixed-precision decimals * @author Compound * @notice Exp is a struct which stores decimals with a fixed precision of 18 decimal places. * Thus, if we wanted to store the 5.1, mantissa would store 5.1e18. That is: * `Exp({mantissa: 5100000000000000000})`. */ contract Exponential is CarefulMath { uint constant expScale = 1e18; uint constant doubleScale = 1e36; uint constant halfExpScale = expScale/2; uint constant mantissaOne = expScale; struct Exp { uint mantissa; } struct Double { uint mantissa; } /** * @dev Creates an exponential from numerator and denominator values. * Note: Returns an error if (`num` * 10e18) > MAX_INT, * or if `denom` is zero. */ function getExp(uint num, uint denom) pure internal returns (MathError, Exp memory) { (MathError err0, uint scaledNumerator) = mulUInt(num, expScale); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } (MathError err1, uint rational) = divUInt(scaledNumerator, denom); if (err1 != MathError.NO_ERROR) { return (err1, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: rational})); } /** * @dev Adds two exponentials, returning a new exponential. */ function addExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError error, uint result) = addUInt(a.mantissa, b.mantissa); return (error, Exp({mantissa: result})); } /** * @dev Subtracts two exponentials, returning a new exponential. */ function subExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError error, uint result) = subUInt(a.mantissa, b.mantissa); return (error, Exp({mantissa: result})); } /** * @dev Multiply an Exp by a scalar, returning a new Exp. */ function mulScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) { (MathError err0, uint scaledMantissa) = mulUInt(a.mantissa, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: scaledMantissa})); } /** * @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer. */ function mulScalarTruncate(Exp memory a, uint scalar) pure internal returns (MathError, uint) { (MathError err, Exp memory product) = mulScalar(a, scalar); if (err != MathError.NO_ERROR) { return (err, 0); } return (MathError.NO_ERROR, truncate(product)); } /** * @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer. */ function mulScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (MathError, uint) { (MathError err, Exp memory product) = mulScalar(a, scalar); if (err != MathError.NO_ERROR) { return (err, 0); } return addUInt(truncate(product), addend); } /** * @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer. */ function mul_ScalarTruncate(Exp memory a, uint scalar) pure internal returns (uint) { Exp memory product = mul_(a, scalar); return truncate(product); } /** * @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer. */ function mul_ScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (uint) { Exp memory product = mul_(a, scalar); return add_(truncate(product), addend); } /** * @dev Divide an Exp by a scalar, returning a new Exp. */ function divScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) { (MathError err0, uint descaledMantissa) = divUInt(a.mantissa, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: descaledMantissa})); } /** * @dev Divide a scalar by an Exp, returning a new Exp. */ function divScalarByExp(uint scalar, Exp memory divisor) pure internal returns (MathError, Exp memory) { /* We are doing this as: getExp(mulUInt(expScale, scalar), divisor.mantissa) How it works: Exp = a / b; Scalar = s; `s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale` */ (MathError err0, uint numerator) = mulUInt(expScale, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return getExp(numerator, divisor.mantissa); } /** * @dev Divide a scalar by an Exp, then truncate to return an unsigned integer. */ function divScalarByExpTruncate(uint scalar, Exp memory divisor) pure internal returns (MathError, uint) { (MathError err, Exp memory fraction) = divScalarByExp(scalar, divisor); if (err != MathError.NO_ERROR) { return (err, 0); } return (MathError.NO_ERROR, truncate(fraction)); } /** * @dev Divide a scalar by an Exp, returning a new Exp. */ function div_ScalarByExp(uint scalar, Exp memory divisor) pure internal returns (Exp memory) { /* We are doing this as: getExp(mulUInt(expScale, scalar), divisor.mantissa) How it works: Exp = a / b; Scalar = s; `s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale` */ uint numerator = mul_(expScale, scalar); return Exp({mantissa: div_(numerator, divisor)}); } /** * @dev Divide a scalar by an Exp, then truncate to return an unsigned integer. */ function div_ScalarByExpTruncate(uint scalar, Exp memory divisor) pure internal returns (uint) { Exp memory fraction = div_ScalarByExp(scalar, divisor); return truncate(fraction); } /** * @dev Multiplies two exponentials, returning a new exponential. */ function mulExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError err0, uint doubleScaledProduct) = mulUInt(a.mantissa, b.mantissa); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } // We add half the scale before dividing so that we get rounding instead of truncation. // See "Listing 6" and text above it at https://accu.org/index.php/journals/1717 // Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18. (MathError err1, uint doubleScaledProductWithHalfScale) = addUInt(halfExpScale, doubleScaledProduct); if (err1 != MathError.NO_ERROR) { return (err1, Exp({mantissa: 0})); } (MathError err2, uint product) = divUInt(doubleScaledProductWithHalfScale, expScale); // The only error `div` can return is MathError.DIVISION_BY_ZERO but we control `expScale` and it is not zero. assert(err2 == MathError.NO_ERROR); return (MathError.NO_ERROR, Exp({mantissa: product})); } /** * @dev Multiplies two exponentials given their mantissas, returning a new exponential. */ function mulExp(uint a, uint b) pure internal returns (MathError, Exp memory) { return mulExp(Exp({mantissa: a}), Exp({mantissa: b})); } /** * @dev Multiplies three exponentials, returning a new exponential. */ function mulExp3(Exp memory a, Exp memory b, Exp memory c) pure internal returns (MathError, Exp memory) { (MathError err, Exp memory ab) = mulExp(a, b); if (err != MathError.NO_ERROR) { return (err, ab); } return mulExp(ab, c); } /** * @dev Divides two exponentials, returning a new exponential. * (a/scale) / (b/scale) = (a/scale) * (scale/b) = a/b, * which we can scale as an Exp by calling getExp(a.mantissa, b.mantissa) */ function divExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { return getExp(a.mantissa, b.mantissa); } /** * @dev Truncates the given exp to a whole number value. * For example, truncate(Exp{mantissa: 15 * expScale}) = 15 */ function truncate(Exp memory exp) pure internal returns (uint) { // Note: We are not using careful math here as we're performing a division that cannot fail return exp.mantissa / expScale; } /** * @dev Checks if first Exp is less than second Exp. */ function lessThanExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa < right.mantissa; } /** * @dev Checks if left Exp <= right Exp. */ function lessThanOrEqualExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa <= right.mantissa; } /** * @dev returns true if Exp is exactly zero */ function isZeroExp(Exp memory value) pure internal returns (bool) { return value.mantissa == 0; } function safe224(uint n, string memory errorMessage) pure internal returns (uint224) { require(n < 2**224, errorMessage); return uint224(n); } function safe32(uint n, string memory errorMessage) pure internal returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function add_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: add_(a.mantissa, b.mantissa)}); } function add_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: add_(a.mantissa, b.mantissa)}); } function add_(uint a, uint b) pure internal returns (uint) { return add_(a, b, "addition overflow"); } function add_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { uint c = a + b; require(c >= a, errorMessage); return c; } function sub_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: sub_(a.mantissa, b.mantissa)}); } function sub_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: sub_(a.mantissa, b.mantissa)}); } function sub_(uint a, uint b) pure internal returns (uint) { return sub_(a, b, "subtraction underflow"); } function sub_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { require(b <= a, errorMessage); return a - b; } function mul_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: mul_(a.mantissa, b.mantissa) / expScale}); } function mul_(Exp memory a, uint b) pure internal returns (Exp memory) { return Exp({mantissa: mul_(a.mantissa, b)}); } function mul_(uint a, Exp memory b) pure internal returns (uint) { return mul_(a, b.mantissa) / expScale; } function mul_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: mul_(a.mantissa, b.mantissa) / doubleScale}); } function mul_(Double memory a, uint b) pure internal returns (Double memory) { return Double({mantissa: mul_(a.mantissa, b)}); } function mul_(uint a, Double memory b) pure internal returns (uint) { return mul_(a, b.mantissa) / doubleScale; } function mul_(uint a, uint b) pure internal returns (uint) { return mul_(a, b, "multiplication overflow"); } function mul_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { if (a == 0 || b == 0) { return 0; } uint c = a * b; require(c / a == b, errorMessage); return c; } function div_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: div_(mul_(a.mantissa, expScale), b.mantissa)}); } function div_(Exp memory a, uint b) pure internal returns (Exp memory) { return Exp({mantissa: div_(a.mantissa, b)}); } function div_(uint a, Exp memory b) pure internal returns (uint) { return div_(mul_(a, expScale), b.mantissa); } function div_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: div_(mul_(a.mantissa, doubleScale), b.mantissa)}); } function div_(Double memory a, uint b) pure internal returns (Double memory) { return Double({mantissa: div_(a.mantissa, b)}); } function div_(uint a, Double memory b) pure internal returns (uint) { return div_(mul_(a, doubleScale), b.mantissa); } function div_(uint a, uint b) pure internal returns (uint) { return div_(a, b, "divide by zero"); } function div_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { require(b > 0, errorMessage); return a / b; } function fraction(uint a, uint b) pure internal returns (Double memory) { return Double({mantissa: div_(mul_(a, doubleScale), b)}); } // implementation from https://github.com/Uniswap/uniswap-lib/commit/99f3f28770640ba1bb1ff460ac7c5292fb8291a0 // original implementation: https://github.com/abdk-consulting/abdk-libraries-solidity/blob/master/ABDKMath64x64.sol#L687 function sqrt(uint x) pure internal returns (uint) { if (x == 0) return 0; uint xx = x; uint r = 1; if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; } if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; } if (xx >= 0x100000000) { xx >>= 32; r <<= 16; } if (xx >= 0x10000) { xx >>= 16; r <<= 8; } if (xx >= 0x100) { xx >>= 8; r <<= 4; } if (xx >= 0x10) { xx >>= 4; r <<= 2; } if (xx >= 0x8) { r <<= 1; } r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; // Seven iterations should be enough uint r1 = x / r; return (r < r1 ? r : r1); } } pragma solidity ^0.5.16; /** * @title Compound's InterestRateModel Interface * @author Compound */ contract InterestRateModel { /// @notice Indicator that this is an InterestRateModel contract (for inspection) bool public constant isInterestRateModel = true; /** * @notice Calculates the current borrow interest rate per block * @param cash The total amount of cash the market has * @param borrows The total amount of borrows the market has outstanding * @param reserves The total amnount of reserves the market has * @return The borrow rate per block (as a percentage, and scaled by 1e18) */ function getBorrowRate(uint cash, uint borrows, uint reserves) external view returns (uint); /** * @notice Calculates the current supply interest rate per block * @param cash The total amount of cash the market has * @param borrows The total amount of borrows the market has outstanding * @param reserves The total amnount of reserves the market has * @param reserveFactorMantissa The current reserve factor the market has * @return The supply rate per block (as a percentage, and scaled by 1e18) */ function getSupplyRate(uint cash, uint borrows, uint reserves, uint reserveFactorMantissa) external view returns (uint); }
We calculate the exchange rate and the amount of underlying to be redeemed: redeemTokens = redeemTokensIn redeemAmount = redeemTokensIn x exchangeRateCurrent/
vars.redeemAmount = mul_ScalarTruncate(Exp({mantissa: vars.exchangeRateMantissa}), redeemTokensIn);
529,987
[ 1, 3218, 4604, 326, 7829, 4993, 471, 326, 3844, 434, 6808, 358, 506, 283, 24903, 329, 30, 225, 283, 24903, 5157, 273, 283, 24903, 5157, 382, 225, 283, 24903, 6275, 273, 283, 24903, 5157, 382, 619, 7829, 4727, 3935, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 5411, 4153, 18, 266, 24903, 6275, 273, 14064, 67, 13639, 25871, 12, 2966, 12590, 81, 970, 21269, 30, 4153, 18, 16641, 4727, 49, 970, 21269, 97, 3631, 283, 24903, 5157, 382, 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 ]
// SPDX-License-Identifier: MIT pragma solidity 0.8.7; import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol"; import {IAnftifyNFT} from "./interfaces/IAnftifyNFT.sol"; contract PreSale is Ownable { struct Voucher { bytes32 r; bytes32 s; uint8 v; } mapping(address => bool) public addressMinted; uint256 public maxMintsPerAddress; uint256 public maxMintsForSaleType; uint256 public totalMinted; uint256 public mintPrice; string public saleType; address public nft; address public treasury; bool public pause = true; event MaxMintsForSaleTypeSet(uint256 maxMintsForSaleType); event MaxMintPerAddressSet(uint256 maxMintsPerAddress); event MintPriceSet(uint256 mintPrice); event SaleTypeSet(string saleType); event NFTAddressSet(address nft); event TreasuryAddressUpdated(address treasury); event PauseUpdated(bool pause); constructor(uint256 _maxMintsForSaleType, uint256 _maxMintsPerAddress, uint256 _mintPrice, string memory _saleType, address _nft, address _treasury) { require(_maxMintsForSaleType > 0, "PreSale: maxMintsForSaleType should be greater than zero"); require(_maxMintsPerAddress > 0, "PreSale: maxMintsPerAddress should be greater than zero"); require(bytes(_saleType).length > 0, "PreSale: Cannot set empty saleType"); require(_nft != address(0), "PreSale: NFT address cannot be zero address"); require(_treasury != address(0), "PreSale: treasury address cannot be zero address"); maxMintsForSaleType = _maxMintsForSaleType; maxMintsPerAddress = _maxMintsPerAddress; mintPrice = _mintPrice; saleType = _saleType; nft = _nft; treasury = _treasury; emit MaxMintsForSaleTypeSet(maxMintsForSaleType); emit MaxMintPerAddressSet(maxMintsPerAddress); emit MintPriceSet(mintPrice); emit SaleTypeSet(saleType); emit NFTAddressSet(nft); emit TreasuryAddressUpdated(treasury); } /// Mint function for presale /// @dev mints by addresses validated using verified vouchers signed by an admin signer /// @notice mints token to addresses eligible for presale /// @param amount number of tokens to mint in transaction /// @param voucher voucher signed by an admin signer function mint(uint256 amount, Voucher memory voucher) external payable validateEthPayment(amount) saleIsOpen(amount) { require( amount > 0, "PreSale: 0 number of presale mints" ); require( amount <= maxMintsPerAddress, "PreSale: Exceeds number of presale mints allowed per address" ); require( !addressMinted[msg.sender], "PreSale: Already minted" ); bytes32 digest = keccak256(abi.encode(saleType, msg.sender)); require(_isVerifiedVoucher(digest, voucher), "PreSale: Invalid voucher"); addressMinted[msg.sender] = true; totalMinted = totalMinted + amount; IAnftifyNFT(nft).mint(amount, msg.sender); (bool success, ) = treasury.call{value: address(this).balance}(""); require(success, "Transfer failed."); } /// @dev check that the voucher sent was signed by the admin signer function _isVerifiedVoucher(bytes32 digest, Voucher memory voucher) internal view returns (bool) { address signer = ecrecover(digest, voucher.v, voucher.r, voucher.s); require(signer != address(0), "ECDSA: invalid signature"); // Added check for zero address return signer == owner(); } function setTreasury(address _treasury) public onlyOwner { require(_treasury != address(0), "PreSale: treasury address cannot be zero address"); treasury = _treasury; emit TreasuryAddressUpdated(treasury); } function setPause(bool _pause) public onlyOwner { pause = _pause; emit PauseUpdated(pause); } /// Modifier to validate eth value on payable functions /// @param amount number of tokens to mint in transaction modifier validateEthPayment(uint256 amount) { require( mintPrice * amount <= msg.value, "PreSale: Ether value sent is not correct" ); _; } modifier saleIsOpen(uint256 amount) { require( totalMinted + amount <= maxMintsForSaleType, "PreSale: Exceeds number of total presale mints allowed" ); require( !pause, "PreSale: Paused" ); _; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.7; import {IERC721Enumerable} from "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol"; interface IAnftifyNFT is IERC721Enumerable { function mint(uint256 amount, address account) external; function setContractURI(string memory _contractURI) external; function setBaseURI(string memory _baseTokenURI) external; function setPause(bool _pause) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol) pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); }
Mint function for presale @dev mints by addresses validated using verified vouchers signed by an admin signer @notice mints token to addresses eligible for presale @param amount number of tokens to mint in transaction @param voucher voucher signed by an admin signer
function mint(uint256 amount, Voucher memory voucher) external payable validateEthPayment(amount) saleIsOpen(amount) { require( amount > 0, "PreSale: 0 number of presale mints" ); require( amount <= maxMintsPerAddress, "PreSale: Exceeds number of presale mints allowed per address" ); require( !addressMinted[msg.sender], "PreSale: Already minted" ); bytes32 digest = keccak256(abi.encode(saleType, msg.sender)); require(_isVerifiedVoucher(digest, voucher), "PreSale: Invalid voucher"); addressMinted[msg.sender] = true; totalMinted = totalMinted + amount; IAnftifyNFT(nft).mint(amount, msg.sender); require(success, "Transfer failed."); }
14,870,583
[ 1, 49, 474, 445, 364, 4075, 5349, 225, 312, 28142, 635, 6138, 10266, 1450, 13808, 331, 31952, 6726, 635, 392, 3981, 10363, 225, 312, 28142, 1147, 358, 6138, 21351, 364, 4075, 5349, 225, 3844, 1300, 434, 2430, 358, 312, 474, 316, 2492, 225, 331, 14329, 331, 14329, 6726, 635, 392, 3981, 10363, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 915, 312, 474, 12, 11890, 5034, 3844, 16, 776, 14329, 3778, 331, 14329, 13, 7010, 202, 202, 9375, 7010, 202, 202, 10239, 429, 7010, 202, 202, 5662, 41, 451, 6032, 12, 8949, 13, 203, 202, 202, 87, 5349, 2520, 3678, 12, 8949, 13, 203, 202, 95, 203, 202, 202, 6528, 12, 203, 1082, 202, 8949, 405, 374, 16, 203, 1082, 202, 6, 1386, 30746, 30, 374, 1300, 434, 4075, 5349, 312, 28142, 6, 203, 202, 202, 1769, 203, 203, 202, 202, 6528, 12, 203, 1082, 202, 8949, 1648, 943, 49, 28142, 2173, 1887, 16, 203, 1082, 202, 6, 1386, 30746, 30, 1312, 5288, 87, 1300, 434, 4075, 5349, 312, 28142, 2935, 1534, 1758, 6, 203, 202, 202, 1769, 203, 203, 202, 202, 6528, 12, 203, 1082, 202, 5, 2867, 49, 474, 329, 63, 3576, 18, 15330, 6487, 203, 1082, 202, 6, 1386, 30746, 30, 17009, 312, 474, 329, 6, 203, 202, 202, 1769, 203, 202, 202, 3890, 1578, 5403, 273, 417, 24410, 581, 5034, 12, 21457, 18, 3015, 12, 87, 5349, 559, 16, 1234, 18, 15330, 10019, 203, 202, 202, 6528, 24899, 291, 24369, 19585, 12, 10171, 16, 331, 14329, 3631, 315, 1386, 30746, 30, 1962, 331, 14329, 8863, 203, 203, 202, 202, 2867, 49, 474, 329, 63, 3576, 18, 15330, 65, 273, 638, 31, 203, 202, 202, 4963, 49, 474, 329, 273, 2078, 49, 474, 329, 397, 3844, 31, 203, 202, 202, 45, 979, 1222, 1164, 50, 4464, 12, 82, 1222, 2934, 81, 474, 12, 8949, 16, 1234, 18, 15330, 1769, 203, 2 ]
/* ___ _ ___ _ | .\ ___ _ _ <_> ___ | __><_>._ _ ___ ._ _ ___ ___ | _// ._>| '_>| ||___|| _> | || ' |<_> || ' |/ | '/ ._> |_| \___.|_| |_| |_| |_||_|_|<___||_|_|\_|_.\___. * PeriFinance: ExchangeRates.sol * * Latest source (may be newer): https://github.com/perifinance/peri-finance/blob/master/contracts/ExchangeRates.sol * Docs: Will be added in the future. * https://docs.peri.finance/contracts/source/contracts/ExchangeRates * * Contract Dependencies: * - IAddressResolver * - IExchangeRates * - MixinResolver * - MixinSystemSettings * - Owned * Libraries: * - SafeDecimalMath * - SafeMath * * MIT License * =========== * * Copyright (c) 2021 PeriFinance * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE */ pragma solidity 0.5.16; // https://docs.peri.finance/contracts/source/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 { _onlyOwner(); _; } function _onlyOwner() private view { require(msg.sender == owner, "Only the contract owner may perform this action"); } event OwnerNominated(address newOwner); event OwnerChanged(address oldOwner, address newOwner); } // https://docs.peri.finance/contracts/source/interfaces/iaddressresolver interface IAddressResolver { function getAddress(bytes32 name) external view returns (address); function getPynth(bytes32 key) external view returns (address); function requireAndGetAddress(bytes32 name, string calldata reason) external view returns (address); } // https://docs.peri.finance/contracts/source/interfaces/ipynth interface IPynth { // Views function currencyKey() external view returns (bytes32); function transferablePynths(address account) external view returns (uint); // Mutative functions function transferAndSettle(address to, uint value) external returns (bool); function transferFromAndSettle( address from, address to, uint value ) external returns (bool); // Restricted: used internally to PeriFinance function burn(address account, uint amount) external; function issue(address account, uint amount) external; } // https://docs.peri.finance/contracts/source/interfaces/iissuer interface IIssuer { // Views function anyPynthOrPERIRateIsInvalid() external view returns (bool anyRateInvalid); function availableCurrencyKeys() external view returns (bytes32[] memory); function availablePynthCount() external view returns (uint); function availablePynths(uint index) external view returns (IPynth); function canBurnPynths(address account) external view returns (bool); function collateral(address account) external view returns (uint); function collateralisationRatio(address issuer) external view returns (uint); function collateralisationRatioAndAnyRatesInvalid(address _issuer) external view returns (uint cratio, bool anyRateIsInvalid); function debtBalanceOf(address issuer, bytes32 currencyKey) external view returns (uint debtBalance); function issuanceRatio() external view returns (uint); function externalTokenLimit() external view returns (uint); function lastIssueEvent(address account) external view returns (uint); function maxIssuablePynths(address issuer) external view returns (uint maxIssuable); function externalTokenQuota( address _account, uint _addtionalpUSD, uint _addtionalExToken, bool _isIssue ) external view returns (uint); function maxExternalTokenStakeAmount(address _account, bytes32 _currencyKey) external view returns (uint issueAmountToQuota, uint stakeAmountToQuota); function minimumStakeTime() external view returns (uint); function remainingIssuablePynths(address issuer) external view returns ( uint maxIssuable, uint alreadyIssued, uint totalSystemDebt ); function pynths(bytes32 currencyKey) external view returns (IPynth); function getPynths(bytes32[] calldata currencyKeys) external view returns (IPynth[] memory); function pynthsByAddress(address pynthAddress) external view returns (bytes32); function totalIssuedPynths(bytes32 currencyKey, bool excludeEtherCollateral) external view returns (uint); function transferablePeriFinanceAndAnyRateIsInvalid(address account, uint balance) external view returns (uint transferable, bool anyRateIsInvalid); // Restricted: used internally to PeriFinance function issuePynths( address _issuer, bytes32 _currencyKey, uint _issueAmount ) external; function issueMaxPynths(address _issuer) external; function issuePynthsToMaxQuota(address _issuer, bytes32 _currencyKey) external; function burnPynths( address _from, bytes32 _currencyKey, uint _burnAmount ) external; function fitToClaimable(address _from) external; function exit(address _from) external; function liquidateDelinquentAccount( address account, uint pusdAmount, address liquidator ) external returns (uint totalRedeemed, uint amountToLiquidate); } // Inheritance // Internal references // https://docs.peri.finance/contracts/source/contracts/addressresolver contract AddressResolver is Owned, IAddressResolver { mapping(bytes32 => address) public repository; constructor(address _owner) public Owned(_owner) {} /* ========== RESTRICTED FUNCTIONS ========== */ function importAddresses(bytes32[] calldata names, address[] calldata destinations) external onlyOwner { require(names.length == destinations.length, "Input lengths must match"); for (uint i = 0; i < names.length; i++) { bytes32 name = names[i]; address destination = destinations[i]; repository[name] = destination; emit AddressImported(name, destination); } } /* ========= PUBLIC FUNCTIONS ========== */ function rebuildCaches(MixinResolver[] calldata destinations) external { for (uint i = 0; i < destinations.length; i++) { destinations[i].rebuildCache(); } } /* ========== VIEWS ========== */ function areAddressesImported(bytes32[] calldata names, address[] calldata destinations) external view returns (bool) { for (uint i = 0; i < names.length; i++) { if (repository[names[i]] != destinations[i]) { return false; } } return true; } function getAddress(bytes32 name) external view returns (address) { return repository[name]; } function requireAndGetAddress(bytes32 name, string calldata reason) external view returns (address) { address _foundAddress = repository[name]; require(_foundAddress != address(0), reason); return _foundAddress; } function getPynth(bytes32 key) external view returns (address) { IIssuer issuer = IIssuer(repository["Issuer"]); require(address(issuer) != address(0), "Cannot find Issuer address"); return address(issuer.pynths(key)); } /* ========== EVENTS ========== */ event AddressImported(bytes32 name, address destination); } // solhint-disable payable-fallback // https://docs.peri.finance/contracts/source/contracts/readproxy contract ReadProxy is Owned { address public target; constructor(address _owner) public Owned(_owner) {} function setTarget(address _target) external onlyOwner { target = _target; emit TargetUpdated(target); } function() external { // The basics of a proxy read call // Note that msg.sender in the underlying will always be the address of this contract. assembly { calldatacopy(0, 0, calldatasize) // Use of staticcall - this will revert if the underlying function mutates state let result := staticcall(gas, sload(target_slot), 0, calldatasize, 0, 0) returndatacopy(0, 0, returndatasize) if iszero(result) { revert(0, returndatasize) } return(0, returndatasize) } } event TargetUpdated(address newTarget); } // Inheritance // Internal references // https://docs.peri.finance/contracts/source/contracts/mixinresolver contract MixinResolver { AddressResolver public resolver; mapping(bytes32 => address) private addressCache; constructor(address _resolver) internal { resolver = AddressResolver(_resolver); } /* ========== INTERNAL FUNCTIONS ========== */ function combineArrays(bytes32[] memory first, bytes32[] memory second) internal pure returns (bytes32[] memory combination) { combination = new bytes32[](first.length + second.length); for (uint i = 0; i < first.length; i++) { combination[i] = first[i]; } for (uint j = 0; j < second.length; j++) { combination[first.length + j] = second[j]; } } /* ========== PUBLIC FUNCTIONS ========== */ // Note: this function is public not external in order for it to be overridden and invoked via super in subclasses function resolverAddressesRequired() public view returns (bytes32[] memory addresses) {} function rebuildCache() public { bytes32[] memory requiredAddresses = resolverAddressesRequired(); // The resolver must call this function whenver it updates its state for (uint i = 0; i < requiredAddresses.length; i++) { bytes32 name = requiredAddresses[i]; // Note: can only be invoked once the resolver has all the targets needed added address destination = resolver.requireAndGetAddress(name, string(abi.encodePacked("Resolver missing target: ", name))); addressCache[name] = destination; emit CacheUpdated(name, destination); } } /* ========== VIEWS ========== */ function isResolverCached() external view returns (bool) { bytes32[] memory requiredAddresses = resolverAddressesRequired(); for (uint i = 0; i < requiredAddresses.length; i++) { bytes32 name = requiredAddresses[i]; // false if our cache is invalid or if the resolver doesn't have the required address if (resolver.getAddress(name) != addressCache[name] || addressCache[name] == address(0)) { return false; } } return true; } /* ========== INTERNAL FUNCTIONS ========== */ function requireAndGetAddress(bytes32 name) internal view returns (address) { address _foundAddress = addressCache[name]; require(_foundAddress != address(0), string(abi.encodePacked("Missing address: ", name))); return _foundAddress; } /* ========== EVENTS ========== */ event CacheUpdated(bytes32 name, address destination); } // https://docs.peri.finance/contracts/source/interfaces/iflexiblestorage interface IFlexibleStorage { // Views function getUIntValue(bytes32 contractName, bytes32 record) external view returns (uint); function getUIntValues(bytes32 contractName, bytes32[] calldata records) external view returns (uint[] memory); function getIntValue(bytes32 contractName, bytes32 record) external view returns (int); function getIntValues(bytes32 contractName, bytes32[] calldata records) external view returns (int[] memory); function getAddressValue(bytes32 contractName, bytes32 record) external view returns (address); function getAddressValues(bytes32 contractName, bytes32[] calldata records) external view returns (address[] memory); function getBoolValue(bytes32 contractName, bytes32 record) external view returns (bool); function getBoolValues(bytes32 contractName, bytes32[] calldata records) external view returns (bool[] memory); function getBytes32Value(bytes32 contractName, bytes32 record) external view returns (bytes32); function getBytes32Values(bytes32 contractName, bytes32[] calldata records) external view returns (bytes32[] memory); // Mutative functions function deleteUIntValue(bytes32 contractName, bytes32 record) external; function deleteIntValue(bytes32 contractName, bytes32 record) external; function deleteAddressValue(bytes32 contractName, bytes32 record) external; function deleteBoolValue(bytes32 contractName, bytes32 record) external; function deleteBytes32Value(bytes32 contractName, bytes32 record) external; function setUIntValue( bytes32 contractName, bytes32 record, uint value ) external; function setUIntValues( bytes32 contractName, bytes32[] calldata records, uint[] calldata values ) external; function setIntValue( bytes32 contractName, bytes32 record, int value ) external; function setIntValues( bytes32 contractName, bytes32[] calldata records, int[] calldata values ) external; function setAddressValue( bytes32 contractName, bytes32 record, address value ) external; function setAddressValues( bytes32 contractName, bytes32[] calldata records, address[] calldata values ) external; function setBoolValue( bytes32 contractName, bytes32 record, bool value ) external; function setBoolValues( bytes32 contractName, bytes32[] calldata records, bool[] calldata values ) external; function setBytes32Value( bytes32 contractName, bytes32 record, bytes32 value ) external; function setBytes32Values( bytes32 contractName, bytes32[] calldata records, bytes32[] calldata values ) external; } // Internal references // https://docs.peri.finance/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_DEPOSIT_GAS_LIMIT = "crossDomainDepositGasLimit"; bytes32 internal constant SETTING_CROSS_DOMAIN_ESCROW_GAS_LIMIT = "crossDomainEscrowGasLimit"; bytes32 internal constant SETTING_CROSS_DOMAIN_REWARD_GAS_LIMIT = "crossDomainRewardGasLimit"; bytes32 internal constant SETTING_CROSS_DOMAIN_WITHDRAWAL_GAS_LIMIT = "crossDomainWithdrawalGasLimit"; bytes32 internal constant SETTING_EXTERNAL_TOKEN_QUOTA = "externalTokenQuota"; bytes32 internal constant CONTRACT_FLEXIBLESTORAGE = "FlexibleStorage"; enum CrossDomainMessageGasLimits {Deposit, Escrow, Reward, Withdrawal} 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 _getGasLimitSetting(CrossDomainMessageGasLimits gasLimitType) internal pure returns (bytes32) { if (gasLimitType == CrossDomainMessageGasLimits.Deposit) { return SETTING_CROSS_DOMAIN_DEPOSIT_GAS_LIMIT; } else if (gasLimitType == CrossDomainMessageGasLimits.Escrow) { return SETTING_CROSS_DOMAIN_ESCROW_GAS_LIMIT; } else if (gasLimitType == CrossDomainMessageGasLimits.Reward) { return SETTING_CROSS_DOMAIN_REWARD_GAS_LIMIT; } else if (gasLimitType == CrossDomainMessageGasLimits.Withdrawal) { return SETTING_CROSS_DOMAIN_WITHDRAWAL_GAS_LIMIT; } else { revert("Unknown gas limit type"); } } function getCrossDomainMessageGasLimit(CrossDomainMessageGasLimits gasLimitType) internal view returns (uint) { return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, _getGasLimitSetting(gasLimitType)); } 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); } function getExternalTokenQuota() internal view returns (uint) { return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_EXTERNAL_TOKEN_QUOTA); } } // https://docs.peri.finance/contracts/source/interfaces/iexchangerates interface IExchangeRates { // Structs struct RateAndUpdatedTime { uint216 rate; uint40 time; } struct InversePricing { uint entryPoint; uint upperLimit; uint lowerLimit; bool frozenAtUpperLimit; bool frozenAtLowerLimit; } // Views function aggregators(bytes32 currencyKey) external view returns (address); function aggregatorWarningFlags() external view returns (address); function anyRateIsInvalid(bytes32[] calldata currencyKeys) external view returns (bool); function canFreezeRate(bytes32 currencyKey) external view returns (bool); function currentRoundForRate(bytes32 currencyKey) external view returns (uint); function currenciesUsingAggregator(address aggregator) external view returns (bytes32[] memory); function effectiveValue( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey ) external view returns (uint value); function effectiveValueAndRates( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey ) external view returns ( uint value, uint sourceRate, uint destinationRate ); function effectiveValueAtRound( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, uint roundIdForSrc, uint roundIdForDest ) external view returns (uint value); function getCurrentRoundId(bytes32 currencyKey) external view returns (uint); function getLastRoundIdBeforeElapsedSecs( bytes32 currencyKey, uint startingRoundId, uint startingTimestamp, uint timediff ) external view returns (uint); function inversePricing(bytes32 currencyKey) external view returns ( uint entryPoint, uint upperLimit, uint lowerLimit, bool frozenAtUpperLimit, bool frozenAtLowerLimit ); function lastRateUpdateTimes(bytes32 currencyKey) external view returns (uint256); function oracle() external view returns (address); function rateAndTimestampAtRound(bytes32 currencyKey, uint roundId) external view returns (uint rate, uint time); function rateAndUpdatedTime(bytes32 currencyKey) external view returns (uint rate, uint time); function rateAndInvalid(bytes32 currencyKey) external view returns (uint rate, bool isInvalid); function rateForCurrency(bytes32 currencyKey) external view returns (uint); function rateIsFlagged(bytes32 currencyKey) external view returns (bool); function rateIsFrozen(bytes32 currencyKey) external view returns (bool); function rateIsInvalid(bytes32 currencyKey) external view returns (bool); function rateIsStale(bytes32 currencyKey) external view returns (bool); function rateStalePeriod() external view returns (uint); function ratesAndUpdatedTimeForCurrencyLastNRounds(bytes32 currencyKey, uint numRounds) external view returns (uint[] memory rates, uint[] memory times); function ratesAndInvalidForCurrencies(bytes32[] calldata currencyKeys) external view returns (uint[] memory rates, bool anyRateInvalid); function ratesForCurrencies(bytes32[] calldata currencyKeys) external view returns (uint[] memory); // Mutative functions function freezeRate(bytes32 currencyKey) external; } /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, "SafeMath: division by zero"); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "SafeMath: modulo by zero"); return a % b; } } // Libraries // https://docs.peri.finance/contracts/source/libraries/safedecimalmath library SafeDecimalMath { using SafeMath for uint; /* Number of decimal places in the representations. */ uint8 public constant decimals = 18; uint8 public constant highPrecisionDecimals = 27; /* The number representing 1.0. */ uint public constant UNIT = 10**uint(decimals); /* The number representing 1.0 for higher fidelity numbers. */ uint public constant PRECISE_UNIT = 10**uint(highPrecisionDecimals); uint private constant UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR = 10**uint(highPrecisionDecimals - decimals); /** * @return Provides an interface to UNIT. */ function unit() external pure returns (uint) { return UNIT; } /** * @return Provides an interface to PRECISE_UNIT. */ function preciseUnit() external pure returns (uint) { return PRECISE_UNIT; } /** * @return The result of multiplying x and y, interpreting the operands as fixed-point * decimals. * * @dev A unit factor is divided out after the product of x and y is evaluated, * so that product must be less than 2**256. As this is an integer division, * the internal division always rounds down. This helps save on gas. Rounding * is more expensive on gas. */ function multiplyDecimal(uint x, uint y) internal pure returns (uint) { /* Divide by UNIT to remove the extra factor introduced by the product. */ return x.mul(y) / UNIT; } /** * @return The result of safely multiplying x and y, interpreting the operands * as fixed-point decimals of the specified precision unit. * * @dev The operands should be in the form of a the specified unit factor which will be * divided out after the product of x and y is evaluated, so that product must be * less than 2**256. * * Unlike multiplyDecimal, this function rounds the result to the nearest increment. * Rounding is useful when you need to retain fidelity for small decimal numbers * (eg. small fractions or percentages). */ function _multiplyDecimalRound( uint x, uint y, uint precisionUnit ) private pure returns (uint) { /* Divide by UNIT to remove the extra factor introduced by the product. */ uint quotientTimesTen = x.mul(y) / (precisionUnit / 10); if (quotientTimesTen % 10 >= 5) { quotientTimesTen += 10; } return quotientTimesTen / 10; } /** * @return The result of safely multiplying x and y, interpreting the operands * as fixed-point decimals of a precise unit. * * @dev The operands should be in the precise unit factor which will be * divided out after the product of x and y is evaluated, so that product must be * less than 2**256. * * Unlike multiplyDecimal, this function rounds the result to the nearest increment. * Rounding is useful when you need to retain fidelity for small decimal numbers * (eg. small fractions or percentages). */ function multiplyDecimalRoundPrecise(uint x, uint y) internal pure returns (uint) { return _multiplyDecimalRound(x, y, PRECISE_UNIT); } /** * @return The result of safely multiplying x and y, interpreting the operands * as fixed-point decimals of a standard unit. * * @dev The operands should be in the standard unit factor which will be * divided out after the product of x and y is evaluated, so that product must be * less than 2**256. * * Unlike multiplyDecimal, this function rounds the result to the nearest increment. * Rounding is useful when you need to retain fidelity for small decimal numbers * (eg. small fractions or percentages). */ function multiplyDecimalRound(uint x, uint y) internal pure returns (uint) { return _multiplyDecimalRound(x, y, UNIT); } /** * @return The result of safely dividing x and y. The return value is a high * precision decimal. * * @dev y is divided after the product of x and the standard precision unit * is evaluated, so the product of x and UNIT must be less than 2**256. As * this is an integer division, the result is always rounded down. * This helps save on gas. Rounding is more expensive on gas. */ function divideDecimal(uint x, uint y) internal pure returns (uint) { /* Reintroduce the UNIT factor that will be divided out by y. */ return x.mul(UNIT).div(y); } /** * @return The result of safely dividing x and y. The return value is as a rounded * decimal in the precision unit specified in the parameter. * * @dev y is divided after the product of x and the specified precision unit * is evaluated, so the product of x and the specified precision unit must * be less than 2**256. The result is rounded to the nearest increment. */ function _divideDecimalRound( uint x, uint y, uint precisionUnit ) private pure returns (uint) { uint resultTimesTen = x.mul(precisionUnit * 10).div(y); if (resultTimesTen % 10 >= 5) { resultTimesTen += 10; } return resultTimesTen / 10; } /** * @return The result of safely dividing x and y. The return value is as a rounded * standard precision decimal. * * @dev y is divided after the product of x and the standard precision unit * is evaluated, so the product of x and the standard precision unit must * be less than 2**256. The result is rounded to the nearest increment. */ function divideDecimalRound(uint x, uint y) internal pure returns (uint) { return _divideDecimalRound(x, y, UNIT); } /** * @return The result of safely dividing x and y. The return value is as a rounded * high precision decimal. * * @dev y is divided after the product of x and the high precision unit * is evaluated, so the product of x and the high precision unit must * be less than 2**256. The result is rounded to the nearest increment. */ function divideDecimalRoundPrecise(uint x, uint y) internal pure returns (uint) { return _divideDecimalRound(x, y, PRECISE_UNIT); } /** * @dev Convert a standard decimal representation to a high precision one. */ function decimalToPreciseDecimal(uint i) internal pure returns (uint) { return i.mul(UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR); } /** * @dev Convert a high precision decimal to a standard decimal representation. */ function preciseDecimalToDecimal(uint i) internal pure returns (uint) { uint quotientTimesTen = i / (UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR / 10); if (quotientTimesTen % 10 >= 5) { quotientTimesTen += 10; } return quotientTimesTen / 10; } /** * @dev Round down the value with given number */ function roundDownDecimal(uint x, uint d) internal pure returns (uint) { return x.div(10**d).mul(10**d); } /** * @dev Round up the value with given number */ function roundUpDecimal(uint x, uint d) internal pure returns (uint) { uint _decimal = 10**d; if (x % _decimal > 0) { x = x.add(10**d); } return x.div(_decimal).mul(_decimal); } } 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); event AnswerUpdated(int256 indexed current, uint256 indexed roundId, uint256 timestamp); event NewRound(uint256 indexed roundId, address indexed startedBy, uint256 startedAt); } interface AggregatorV3Interface { function decimals() external view returns (uint8); function description() external view returns (string memory); function version() external view returns (uint256); // getRoundData and latestRoundData should both raise "No data present" // if they do not have data to report, instead of returning unset values // which could be misinterpreted as actual reported values. function getRoundData(uint80 _roundId) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function latestRoundData() external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); } /** * @title The V2 & V3 Aggregator Interface * @notice Solidity V0.5 does not allow interfaces to inherit from other * interfaces so this contract is a combination of v0.5 AggregatorInterface.sol * and v0.5 AggregatorV3Interface.sol. */ interface AggregatorV2V3Interface { // // V2 Interface: // 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, uint256 startedAt); // // V3 Interface: // function decimals() external view returns (uint8); function description() external view returns (string memory); function version() external view returns (uint256); // getRoundData and latestRoundData should both raise "No data present" // if they do not have data to report, instead of returning unset values // which could be misinterpreted as actual reported values. function getRoundData(uint80 _roundId) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function latestRoundData() external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); } interface FlagsInterface { function getFlag(address) external view returns (bool); function getFlags(address[] calldata) external view returns (bool[] memory); function raiseFlag(address) external; function raiseFlags(address[] calldata) external; function lowerFlags(address[] calldata) external; function setRaisingAccessController(address) external; } interface IVirtualPynth { // Views function balanceOfUnderlying(address account) external view returns (uint); function rate() external view returns (uint); function readyToSettle() external view returns (bool); function secsLeftInWaitingPeriod() external view returns (uint); function settled() external view returns (bool); function pynth() external view returns (IPynth); // Mutative functions function settle(address account) external; } // https://docs.peri.finance/contracts/source/interfaces/iexchanger interface IExchanger { // Views function calculateAmountAfterSettlement( address from, bytes32 currencyKey, uint amount, uint refunded ) external view returns (uint amountAfterSettlement); function isPynthRateInvalid(bytes32 currencyKey) external view returns (bool); function maxSecsLeftInWaitingPeriod(address account, bytes32 currencyKey) external view returns (uint); function settlementOwing(address account, bytes32 currencyKey) external view returns ( uint reclaimAmount, uint rebateAmount, uint numEntries ); function hasWaitingPeriodOrSettlementOwing(address account, bytes32 currencyKey) external view returns (bool); function feeRateForExchange(bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey) external view returns (uint exchangeFeeRate); function getAmountsForExchange( uint sourceAmount, bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey ) external view returns ( uint amountReceived, uint fee, uint exchangeFeeRate ); function priceDeviationThresholdFactor() external view returns (uint); function waitingPeriodSecs() external view returns (uint); // Mutative functions function exchange( address from, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address destinationAddress ) external returns (uint amountReceived); function exchangeOnBehalf( address exchangeForAddress, address from, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey ) external returns (uint amountReceived); function exchangeWithTracking( address from, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address destinationAddress, address originator, bytes32 trackingCode ) external returns (uint amountReceived); function exchangeOnBehalfWithTracking( address exchangeForAddress, address from, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address originator, bytes32 trackingCode ) external returns (uint amountReceived); function exchangeWithVirtual( address from, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address destinationAddress, bytes32 trackingCode ) external returns (uint amountReceived, IVirtualPynth vPynth); function settle(address from, bytes32 currencyKey) external returns ( uint reclaimed, uint refunded, uint numEntries ); function setLastExchangeRateForPynth(bytes32 currencyKey, uint rate) external; function suspendPynthWithInvalidRate(bytes32 currencyKey) external; } // Inheritance // Libraries // Internal references // AggregatorInterface from Chainlink represents a decentralized pricing network for a single currency key // FlagsInterface from Chainlink addresses SIP-76 interface IExternalRateAggregator { function getRateAndUpdatedTime(bytes32 _currencyKey) external view returns (uint, uint); } // https://docs.peri.finance/contracts/source/contracts/exchangerates contract ExchangeRates is Owned, MixinSystemSettings, IExchangeRates { using SafeMath for uint; using SafeDecimalMath for uint; // Exchange rates and update times stored by currency code, e.g. 'PERI', or 'pUSD' mapping(bytes32 => mapping(uint => RateAndUpdatedTime)) private _rates; // The address of the oracle which pushes rate updates to this contract address public oracle; address public externalRateAggregator; mapping(bytes32 => bool) public currencyByExternal; // Decentralized oracle networks that feed into pricing aggregators mapping(bytes32 => AggregatorV2V3Interface) public aggregators; mapping(bytes32 => uint8) public currencyKeyDecimals; // List of aggregator keys for convenient iteration bytes32[] public aggregatorKeys; // Do not allow the oracle to submit times any further forward into the future than this constant. uint private constant ORACLE_FUTURE_LIMIT = 10 minutes; mapping(bytes32 => InversePricing) public inversePricing; bytes32[] public invertedKeys; mapping(bytes32 => uint) public currentRoundForRate; mapping(bytes32 => uint) public roundFrozen; /* ========== ADDRESS RESOLVER CONFIGURATION ========== */ bytes32 private constant CONTRACT_EXCHANGER = "Exchanger"; // // ========== CONSTRUCTOR ========== constructor( address _owner, address _oracle, address _resolver, bytes32[] memory _currencyKeys, uint[] memory _newRates ) public Owned(_owner) MixinSystemSettings(_resolver) { require(_currencyKeys.length == _newRates.length, "Currency key length and rate length must match."); oracle = _oracle; // The pUSD rate is always 1 and is never stale. _setRate("pUSD", SafeDecimalMath.unit(), now); internalUpdateRates(_currencyKeys, _newRates, now); } /* ========== SETTERS ========== */ function setOracle(address _oracle) external onlyOwner { oracle = _oracle; emit OracleUpdated(oracle); } function setExternalRateAggregator(address _aggregator) external onlyOwner { externalRateAggregator = _aggregator; } function setCurrencyToExternalAggregator(bytes32 _currencyKey, bool _set) external onlyOwner { currencyByExternal[_currencyKey] = _set; } /* ========== MUTATIVE FUNCTIONS ========== */ function updateRates( bytes32[] calldata currencyKeys, uint[] calldata newRates, uint timeSent ) external onlyOracle returns (bool) { return internalUpdateRates(currencyKeys, newRates, timeSent); } function deleteRate(bytes32 currencyKey) external onlyOracle { require(_getRate(currencyKey) > 0, "Rate is zero"); delete _rates[currencyKey][currentRoundForRate[currencyKey]]; currentRoundForRate[currencyKey]--; emit RateDeleted(currencyKey); } function setInversePricing( bytes32 currencyKey, uint entryPoint, uint upperLimit, uint lowerLimit, bool freezeAtUpperLimit, bool freezeAtLowerLimit ) external onlyOwner { // 0 < lowerLimit < entryPoint => 0 < entryPoint require(lowerLimit > 0, "lowerLimit must be above 0"); require(upperLimit > entryPoint, "upperLimit must be above the entryPoint"); require(upperLimit < entryPoint.mul(2), "upperLimit must be less than double entryPoint"); require(lowerLimit < entryPoint, "lowerLimit must be below the entryPoint"); require(!(freezeAtUpperLimit && freezeAtLowerLimit), "Cannot freeze at both limits"); InversePricing storage inverse = inversePricing[currencyKey]; if (inverse.entryPoint == 0) { // then we are adding a new inverse pricing, so add this invertedKeys.push(currencyKey); } inverse.entryPoint = entryPoint; inverse.upperLimit = upperLimit; inverse.lowerLimit = lowerLimit; if (freezeAtUpperLimit || freezeAtLowerLimit) { // When indicating to freeze, we need to know the rate to freeze it at - either upper or lower // this is useful in situations where ExchangeRates is updated and there are existing inverted // rates already frozen in the current contract that need persisting across the upgrade inverse.frozenAtUpperLimit = freezeAtUpperLimit; inverse.frozenAtLowerLimit = freezeAtLowerLimit; uint roundId = _getCurrentRoundId(currencyKey); roundFrozen[currencyKey] = roundId; emit InversePriceFrozen(currencyKey, freezeAtUpperLimit ? upperLimit : lowerLimit, roundId, msg.sender); } else { // unfreeze if need be inverse.frozenAtUpperLimit = false; inverse.frozenAtLowerLimit = false; // remove any tracking roundFrozen[currencyKey] = 0; } // SIP-78 uint rate = _getRate(currencyKey); if (rate > 0) { exchanger().setLastExchangeRateForPynth(currencyKey, rate); } emit InversePriceConfigured(currencyKey, entryPoint, upperLimit, lowerLimit); } function removeInversePricing(bytes32 currencyKey) external onlyOwner { require(inversePricing[currencyKey].entryPoint > 0, "No inverted price exists"); delete inversePricing[currencyKey]; // now remove inverted key from array bool wasRemoved = removeFromArray(currencyKey, invertedKeys); if (wasRemoved) { emit InversePriceConfigured(currencyKey, 0, 0, 0); } } function addAggregator(bytes32 currencyKey, address aggregatorAddress) external onlyOwner { AggregatorV2V3Interface aggregator = AggregatorV2V3Interface(aggregatorAddress); // This check tries to make sure that a valid aggregator is being added. // It checks if the aggregator is an existing smart contract that has implemented `latestTimestamp` function. require(aggregator.latestRound() >= 0, "Given Aggregator is invalid"); uint8 decimals = aggregator.decimals(); require(decimals <= 18, "Aggregator decimals should be lower or equal to 18"); if (address(aggregators[currencyKey]) == address(0)) { aggregatorKeys.push(currencyKey); } aggregators[currencyKey] = aggregator; currencyKeyDecimals[currencyKey] = decimals; emit AggregatorAdded(currencyKey, address(aggregator)); } function removeAggregator(bytes32 currencyKey) external onlyOwner { address aggregator = address(aggregators[currencyKey]); require(aggregator != address(0), "No aggregator exists for key"); delete aggregators[currencyKey]; delete currencyKeyDecimals[currencyKey]; bool wasRemoved = removeFromArray(currencyKey, aggregatorKeys); if (wasRemoved) { emit AggregatorRemoved(currencyKey, aggregator); } } // SIP-75 Public keeper function to freeze a pynth that is out of bounds function freezeRate(bytes32 currencyKey) external { InversePricing storage inverse = inversePricing[currencyKey]; require(inverse.entryPoint > 0, "Cannot freeze non-inverse rate"); require(!inverse.frozenAtUpperLimit && !inverse.frozenAtLowerLimit, "The rate is already frozen"); uint rate = _getRate(currencyKey); if (rate > 0 && (rate >= inverse.upperLimit || rate <= inverse.lowerLimit)) { inverse.frozenAtUpperLimit = (rate == inverse.upperLimit); inverse.frozenAtLowerLimit = (rate == inverse.lowerLimit); uint currentRoundId = _getCurrentRoundId(currencyKey); roundFrozen[currencyKey] = currentRoundId; emit InversePriceFrozen(currencyKey, rate, currentRoundId, msg.sender); } else { revert("Rate within bounds"); } } /* ========== VIEWS ========== */ function resolverAddressesRequired() public view returns (bytes32[] memory addresses) { bytes32[] memory existingAddresses = MixinSystemSettings.resolverAddressesRequired(); bytes32[] memory newAddresses = new bytes32[](1); newAddresses[0] = CONTRACT_EXCHANGER; addresses = combineArrays(existingAddresses, newAddresses); } // SIP-75 View to determine if freezeRate can be called safely function canFreezeRate(bytes32 currencyKey) external view returns (bool) { InversePricing memory inverse = inversePricing[currencyKey]; if (inverse.entryPoint == 0 || inverse.frozenAtUpperLimit || inverse.frozenAtLowerLimit) { return false; } else { uint rate = _getRate(currencyKey); return (rate > 0 && (rate >= inverse.upperLimit || rate <= inverse.lowerLimit)); } } function currenciesUsingAggregator(address aggregator) external view returns (bytes32[] memory currencies) { uint count = 0; currencies = new bytes32[](aggregatorKeys.length); for (uint i = 0; i < aggregatorKeys.length; i++) { bytes32 currencyKey = aggregatorKeys[i]; if (address(aggregators[currencyKey]) == aggregator) { currencies[count++] = currencyKey; } } } function rateStalePeriod() external view returns (uint) { return getRateStalePeriod(); } function aggregatorWarningFlags() external view returns (address) { return getAggregatorWarningFlags(); } function rateAndUpdatedTime(bytes32 currencyKey) external view returns (uint rate, uint time) { RateAndUpdatedTime memory rateAndTime = _getRateAndUpdatedTime(currencyKey); return (rateAndTime.rate, rateAndTime.time); } function getLastRoundIdBeforeElapsedSecs( bytes32 currencyKey, uint startingRoundId, uint startingTimestamp, uint timediff ) external view returns (uint) { uint roundId = startingRoundId; uint nextTimestamp = 0; while (true) { (, nextTimestamp) = _getRateAndTimestampAtRound(currencyKey, roundId + 1); // if there's no new round, then the previous roundId was the latest if (nextTimestamp == 0 || nextTimestamp > startingTimestamp + timediff) { return roundId; } roundId++; } return roundId; } function getCurrentRoundId(bytes32 currencyKey) external view returns (uint) { return _getCurrentRoundId(currencyKey); } function effectiveValueAtRound( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, uint roundIdForSrc, uint roundIdForDest ) external view returns (uint value) { // If there's no change in the currency, then just return the amount they gave us if (sourceCurrencyKey == destinationCurrencyKey) return sourceAmount; (uint srcRate, ) = _getRateAndTimestampAtRound(sourceCurrencyKey, roundIdForSrc); (uint destRate, ) = _getRateAndTimestampAtRound(destinationCurrencyKey, roundIdForDest); if (destRate == 0) { // prevent divide-by 0 error (this can happen when roundIDs jump epochs due // to aggregator upgrades) return 0; } // Calculate the effective value by going from source -> USD -> destination value = sourceAmount.multiplyDecimalRound(srcRate).divideDecimalRound(destRate); } function rateAndTimestampAtRound(bytes32 currencyKey, uint roundId) external view returns (uint rate, uint time) { return _getRateAndTimestampAtRound(currencyKey, roundId); } function lastRateUpdateTimes(bytes32 currencyKey) external view returns (uint256) { return _getUpdatedTime(currencyKey); } function lastRateUpdateTimesForCurrencies(bytes32[] calldata currencyKeys) external view returns (uint[] memory) { uint[] memory lastUpdateTimes = new uint[](currencyKeys.length); for (uint i = 0; i < currencyKeys.length; i++) { lastUpdateTimes[i] = _getUpdatedTime(currencyKeys[i]); } return lastUpdateTimes; } function effectiveValue( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey ) external view returns (uint value) { (value, , ) = _effectiveValueAndRates(sourceCurrencyKey, sourceAmount, destinationCurrencyKey); } function effectiveValueAndRates( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey ) external view returns ( uint value, uint sourceRate, uint destinationRate ) { return _effectiveValueAndRates(sourceCurrencyKey, sourceAmount, destinationCurrencyKey); } function rateForCurrency(bytes32 currencyKey) external view returns (uint) { return _getRateAndUpdatedTime(currencyKey).rate; } function ratesAndUpdatedTimeForCurrencyLastNRounds(bytes32 currencyKey, uint numRounds) external view returns (uint[] memory rates, uint[] memory times) { rates = new uint[](numRounds); times = new uint[](numRounds); uint roundId = _getCurrentRoundId(currencyKey); for (uint i = 0; i < numRounds; i++) { // fetch the rate and treat is as current, so inverse limits if frozen will always be applied // regardless of current rate (rates[i], times[i]) = _getRateAndTimestampAtRound(currencyKey, roundId); if (roundId == 0) { // if we hit the last round, then return what we have return (rates, times); } else { roundId--; } } } function ratesForCurrencies(bytes32[] calldata currencyKeys) external view returns (uint[] memory) { uint[] memory _localRates = new uint[](currencyKeys.length); for (uint i = 0; i < currencyKeys.length; i++) { _localRates[i] = _getRate(currencyKeys[i]); } return _localRates; } function rateAndInvalid(bytes32 currencyKey) external view returns (uint rate, bool isInvalid) { RateAndUpdatedTime memory rateAndTime = _getRateAndUpdatedTime(currencyKey); if (currencyKey == "pUSD") { return (rateAndTime.rate, false); } return ( rateAndTime.rate, _rateIsStaleWithTime(getRateStalePeriod(), rateAndTime.time) || _rateIsFlagged(currencyKey, FlagsInterface(getAggregatorWarningFlags())) ); } function ratesAndInvalidForCurrencies(bytes32[] calldata currencyKeys) external view returns (uint[] memory rates, bool anyRateInvalid) { rates = new uint[](currencyKeys.length); uint256 _rateStalePeriod = getRateStalePeriod(); // fetch all flags at once bool[] memory flagList = getFlagsForRates(currencyKeys); for (uint i = 0; i < currencyKeys.length; i++) { // do one lookup of the rate & time to minimize gas RateAndUpdatedTime memory rateEntry = _getRateAndUpdatedTime(currencyKeys[i]); rates[i] = rateEntry.rate; if (!anyRateInvalid && currencyKeys[i] != "pUSD") { anyRateInvalid = flagList[i] || _rateIsStaleWithTime(_rateStalePeriod, rateEntry.time); } } } function rateIsStale(bytes32 currencyKey) external view returns (bool) { return _rateIsStale(currencyKey, getRateStalePeriod()); } function rateIsFrozen(bytes32 currencyKey) external view returns (bool) { return _rateIsFrozen(currencyKey); } function rateIsInvalid(bytes32 currencyKey) external view returns (bool) { return _rateIsStale(currencyKey, getRateStalePeriod()) || _rateIsFlagged(currencyKey, FlagsInterface(getAggregatorWarningFlags())); } function rateIsFlagged(bytes32 currencyKey) external view returns (bool) { return _rateIsFlagged(currencyKey, FlagsInterface(getAggregatorWarningFlags())); } function anyRateIsInvalid(bytes32[] calldata currencyKeys) external view returns (bool) { // Loop through each key and check whether the data point is stale. uint256 _rateStalePeriod = getRateStalePeriod(); bool[] memory flagList = getFlagsForRates(currencyKeys); for (uint i = 0; i < currencyKeys.length; i++) { if (flagList[i] || _rateIsStale(currencyKeys[i], _rateStalePeriod)) { return true; } } return false; } /* ========== INTERNAL FUNCTIONS ========== */ function exchanger() internal view returns (IExchanger) { return IExchanger(requireAndGetAddress(CONTRACT_EXCHANGER)); } function getFlagsForRates(bytes32[] memory currencyKeys) internal view returns (bool[] memory flagList) { FlagsInterface _flags = FlagsInterface(getAggregatorWarningFlags()); // fetch all flags at once if (_flags != FlagsInterface(0)) { address[] memory _aggregators = new address[](currencyKeys.length); for (uint i = 0; i < currencyKeys.length; i++) { _aggregators[i] = address(aggregators[currencyKeys[i]]); } flagList = _flags.getFlags(_aggregators); } else { flagList = new bool[](currencyKeys.length); } } function _setRate( bytes32 currencyKey, uint256 rate, uint256 time ) internal { // Note: this will effectively start the rounds at 1, which matches Chainlink's Agggregators currentRoundForRate[currencyKey]++; _rates[currencyKey][currentRoundForRate[currencyKey]] = RateAndUpdatedTime({ rate: uint216(rate), time: uint40(time) }); } function internalUpdateRates( bytes32[] memory currencyKeys, uint[] memory newRates, uint timeSent ) internal returns (bool) { require(currencyKeys.length == newRates.length, "Currency key array length must match rates array length."); require(timeSent < (now + ORACLE_FUTURE_LIMIT), "Time is too far into the future"); // Loop through each key and perform update. for (uint i = 0; i < currencyKeys.length; i++) { bytes32 currencyKey = currencyKeys[i]; // Should not set any rate to zero ever, as no asset will ever be // truely worthless and still valid. In this scenario, we should // delete the rate and remove it from the system. require(newRates[i] != 0, "Zero is not a valid rate, please call deleteRate instead."); require(currencyKey != "pUSD", "Rate of pUSD cannot be updated, it's always UNIT."); // We should only update the rate if it's at least the same age as the last rate we've got. if (timeSent < _getUpdatedTime(currencyKey)) { continue; } // Ok, go ahead with the update. _setRate(currencyKey, newRates[i], timeSent); } emit RatesUpdated(currencyKeys, newRates); return true; } function removeFromArray(bytes32 entry, bytes32[] storage array) internal returns (bool) { for (uint i = 0; i < array.length; i++) { if (array[i] == entry) { delete array[i]; // Copy the last key into the place of the one we just deleted // If there's only one key, this is array[0] = array[0]. // If we're deleting the last one, it's also a NOOP in the same way. array[i] = array[array.length - 1]; // Decrease the size of the array by one. array.length--; return true; } } return false; } function _rateOrInverted( bytes32 currencyKey, uint rate, uint roundId ) internal view returns (uint newRate) { // if an inverse mapping exists, adjust the price accordingly InversePricing memory inverse = inversePricing[currencyKey]; if (inverse.entryPoint == 0 || rate == 0) { // when no inverse is set or when given a 0 rate, return the rate, regardless of the inverse status // (the latter is so when a new inverse is set but the underlying has no rate, it will return 0 as // the rate, not the lowerLimit) return rate; } newRate = rate; // Determine when round was frozen (if any) uint roundWhenRateFrozen = roundFrozen[currencyKey]; // And if we're looking at a rate after frozen, and it's currently frozen, then apply the bounds limit even // if the current price is back within bounds if (roundId >= roundWhenRateFrozen && inverse.frozenAtUpperLimit) { newRate = inverse.upperLimit; } else if (roundId >= roundWhenRateFrozen && inverse.frozenAtLowerLimit) { newRate = inverse.lowerLimit; } else { // this ensures any rate outside the limit will never be returned uint doubleEntryPoint = inverse.entryPoint.mul(2); if (doubleEntryPoint <= rate) { // avoid negative numbers for unsigned ints, so set this to 0 // which by the requirement that lowerLimit be > 0 will // cause this to freeze the price to the lowerLimit newRate = 0; } else { newRate = doubleEntryPoint.sub(rate); } // now ensure the rate is between the bounds if (newRate >= inverse.upperLimit) { newRate = inverse.upperLimit; } else if (newRate <= inverse.lowerLimit) { newRate = inverse.lowerLimit; } } } function _formatAggregatorAnswer(bytes32 currencyKey, int256 rate) internal view returns (uint) { require(rate >= 0, "Negative rate not supported"); if (currencyKeyDecimals[currencyKey] > 0) { uint multiplier = 10**uint(SafeMath.sub(18, currencyKeyDecimals[currencyKey])); return uint(uint(rate).mul(multiplier)); } return uint(rate); } function _getRateAndUpdatedTime(bytes32 currencyKey) internal view returns (RateAndUpdatedTime memory) { if (currencyByExternal[currencyKey]) { require(externalRateAggregator != address(0), "External price aggregator is not set yet"); IExternalRateAggregator _externalRateAggregator = IExternalRateAggregator(externalRateAggregator); (uint rate, uint time) = _externalRateAggregator.getRateAndUpdatedTime(currencyKey); return RateAndUpdatedTime({rate: uint216(rate), time: uint40(time)}); } AggregatorV2V3Interface aggregator = aggregators[currencyKey]; if (aggregator != AggregatorV2V3Interface(0)) { // this view from the aggregator is the most gas efficient but it can throw when there's no data, // so let's call it low-level to suppress any reverts bytes memory payload = abi.encodeWithSignature("latestRoundData()"); // solhint-disable avoid-low-level-calls (bool success, bytes memory returnData) = address(aggregator).staticcall(payload); if (success) { (uint80 roundId, int256 answer, , uint256 updatedAt, ) = abi.decode(returnData, (uint80, int256, uint256, uint256, uint80)); return RateAndUpdatedTime({ rate: uint216(_rateOrInverted(currencyKey, _formatAggregatorAnswer(currencyKey, answer), roundId)), time: uint40(updatedAt) }); } } else { uint roundId = currentRoundForRate[currencyKey]; RateAndUpdatedTime memory entry = _rates[currencyKey][roundId]; return RateAndUpdatedTime({rate: uint216(_rateOrInverted(currencyKey, entry.rate, roundId)), time: entry.time}); } } function _getCurrentRoundId(bytes32 currencyKey) internal view returns (uint) { AggregatorV2V3Interface aggregator = aggregators[currencyKey]; if (aggregator != AggregatorV2V3Interface(0)) { return aggregator.latestRound(); } else { return currentRoundForRate[currencyKey]; } } function _getRateAndTimestampAtRound(bytes32 currencyKey, uint roundId) internal view returns (uint rate, uint time) { AggregatorV2V3Interface aggregator = aggregators[currencyKey]; if (aggregator != AggregatorV2V3Interface(0)) { // this view from the aggregator is the most gas efficient but it can throw when there's no data, // so let's call it low-level to suppress any reverts bytes memory payload = abi.encodeWithSignature("getRoundData(uint80)", roundId); // solhint-disable avoid-low-level-calls (bool success, bytes memory returnData) = address(aggregator).staticcall(payload); if (success) { (, int256 answer, , uint256 updatedAt, ) = abi.decode(returnData, (uint80, int256, uint256, uint256, uint80)); return (_rateOrInverted(currencyKey, _formatAggregatorAnswer(currencyKey, answer), roundId), updatedAt); } } else { RateAndUpdatedTime memory update = _rates[currencyKey][roundId]; return (_rateOrInverted(currencyKey, update.rate, roundId), update.time); } } function _getRate(bytes32 currencyKey) internal view returns (uint256) { return _getRateAndUpdatedTime(currencyKey).rate; } function _getUpdatedTime(bytes32 currencyKey) internal view returns (uint256) { return _getRateAndUpdatedTime(currencyKey).time; } function _effectiveValueAndRates( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey ) internal view returns ( uint value, uint sourceRate, uint destinationRate ) { sourceRate = _getRate(sourceCurrencyKey); // If there's no change in the currency, then just return the amount they gave us if (sourceCurrencyKey == destinationCurrencyKey) { destinationRate = sourceRate; value = sourceAmount; } else { // Calculate the effective value by going from source -> USD -> destination destinationRate = _getRate(destinationCurrencyKey); // prevent divide-by 0 error (this happens if the dest is not a valid rate) if (destinationRate > 0) { value = sourceAmount.multiplyDecimalRound(sourceRate).divideDecimalRound(destinationRate); } } } function _rateIsStale(bytes32 currencyKey, uint _rateStalePeriod) internal view returns (bool) { // pUSD is a special case and is never stale (check before an SLOAD of getRateAndUpdatedTime) if (currencyKey == "pUSD") return false; return _rateIsStaleWithTime(_rateStalePeriod, _getUpdatedTime(currencyKey)); } function _rateIsStaleWithTime(uint _rateStalePeriod, uint _time) internal view returns (bool) { return _time.add(_rateStalePeriod) < now; } function _rateIsFrozen(bytes32 currencyKey) internal view returns (bool) { InversePricing memory inverse = inversePricing[currencyKey]; return inverse.frozenAtUpperLimit || inverse.frozenAtLowerLimit; } function _rateIsFlagged(bytes32 currencyKey, FlagsInterface flags) internal view returns (bool) { // pUSD is a special case and is never invalid if (currencyKey == "pUSD") return false; address aggregator = address(aggregators[currencyKey]); // when no aggregator or when the flags haven't been setup if (aggregator == address(0) || flags == FlagsInterface(0)) { return false; } return flags.getFlag(aggregator); } /* ========== MODIFIERS ========== */ modifier onlyOracle { _onlyOracle(); _; } function _onlyOracle() internal view { require(msg.sender == oracle, "Only the oracle can perform this action"); } /* ========== EVENTS ========== */ event OracleUpdated(address newOracle); event RatesUpdated(bytes32[] currencyKeys, uint[] newRates); event RateDeleted(bytes32 currencyKey); event InversePriceConfigured(bytes32 currencyKey, uint entryPoint, uint upperLimit, uint lowerLimit); event InversePriceFrozen(bytes32 currencyKey, uint rate, uint roundId, address initiator); event AggregatorAdded(bytes32 currencyKey, address aggregator); event AggregatorRemoved(bytes32 currencyKey, address aggregator); }
https:docs.peri.finance/contracts/source/contracts/exchangerates Exchange rates and update times stored by currency code, e.g. 'PERI', or 'pUSD' The address of the oracle which pushes rate updates to this contract Decentralized oracle networks that feed into pricing aggregators List of aggregator keys for convenient iteration Do not allow the oracle to submit times any further forward into the future than this constant. ========== CONSTRUCTOR ==========
contract ExchangeRates is Owned, MixinSystemSettings, IExchangeRates { using SafeMath for uint; using SafeDecimalMath for uint; mapping(bytes32 => mapping(uint => RateAndUpdatedTime)) private _rates; address public oracle; address public externalRateAggregator; mapping(bytes32 => bool) public currencyByExternal; mapping(bytes32 => AggregatorV2V3Interface) public aggregators; mapping(bytes32 => uint8) public currencyKeyDecimals; bytes32[] public aggregatorKeys; uint private constant ORACLE_FUTURE_LIMIT = 10 minutes; mapping(bytes32 => InversePricing) public inversePricing; bytes32[] public invertedKeys; mapping(bytes32 => uint) public currentRoundForRate; mapping(bytes32 => uint) public roundFrozen; bytes32 private constant CONTRACT_EXCHANGER = "Exchanger"; constructor( address _owner, address _oracle, address _resolver, bytes32[] memory _currencyKeys, uint[] memory _newRates ) public Owned(_owner) MixinSystemSettings(_resolver) { require(_currencyKeys.length == _newRates.length, "Currency key length and rate length must match."); oracle = _oracle; _setRate("pUSD", SafeDecimalMath.unit(), now); internalUpdateRates(_currencyKeys, _newRates, now); } function setOracle(address _oracle) external onlyOwner { oracle = _oracle; emit OracleUpdated(oracle); } function setExternalRateAggregator(address _aggregator) external onlyOwner { externalRateAggregator = _aggregator; } function setCurrencyToExternalAggregator(bytes32 _currencyKey, bool _set) external onlyOwner { currencyByExternal[_currencyKey] = _set; } function updateRates( bytes32[] calldata currencyKeys, uint[] calldata newRates, uint timeSent ) external onlyOracle returns (bool) { return internalUpdateRates(currencyKeys, newRates, timeSent); } function deleteRate(bytes32 currencyKey) external onlyOracle { require(_getRate(currencyKey) > 0, "Rate is zero"); delete _rates[currencyKey][currentRoundForRate[currencyKey]]; currentRoundForRate[currencyKey]--; emit RateDeleted(currencyKey); } function setInversePricing( bytes32 currencyKey, uint entryPoint, uint upperLimit, uint lowerLimit, bool freezeAtUpperLimit, bool freezeAtLowerLimit ) external onlyOwner { require(lowerLimit > 0, "lowerLimit must be above 0"); require(upperLimit > entryPoint, "upperLimit must be above the entryPoint"); require(upperLimit < entryPoint.mul(2), "upperLimit must be less than double entryPoint"); require(lowerLimit < entryPoint, "lowerLimit must be below the entryPoint"); require(!(freezeAtUpperLimit && freezeAtLowerLimit), "Cannot freeze at both limits"); InversePricing storage inverse = inversePricing[currencyKey]; if (inverse.entryPoint == 0) { invertedKeys.push(currencyKey); } inverse.entryPoint = entryPoint; inverse.upperLimit = upperLimit; inverse.lowerLimit = lowerLimit; if (freezeAtUpperLimit || freezeAtLowerLimit) { inverse.frozenAtUpperLimit = freezeAtUpperLimit; inverse.frozenAtLowerLimit = freezeAtLowerLimit; uint roundId = _getCurrentRoundId(currencyKey); roundFrozen[currencyKey] = roundId; emit InversePriceFrozen(currencyKey, freezeAtUpperLimit ? upperLimit : lowerLimit, roundId, msg.sender); inverse.frozenAtUpperLimit = false; inverse.frozenAtLowerLimit = false; roundFrozen[currencyKey] = 0; } if (rate > 0) { exchanger().setLastExchangeRateForPynth(currencyKey, rate); } emit InversePriceConfigured(currencyKey, entryPoint, upperLimit, lowerLimit); } function setInversePricing( bytes32 currencyKey, uint entryPoint, uint upperLimit, uint lowerLimit, bool freezeAtUpperLimit, bool freezeAtLowerLimit ) external onlyOwner { require(lowerLimit > 0, "lowerLimit must be above 0"); require(upperLimit > entryPoint, "upperLimit must be above the entryPoint"); require(upperLimit < entryPoint.mul(2), "upperLimit must be less than double entryPoint"); require(lowerLimit < entryPoint, "lowerLimit must be below the entryPoint"); require(!(freezeAtUpperLimit && freezeAtLowerLimit), "Cannot freeze at both limits"); InversePricing storage inverse = inversePricing[currencyKey]; if (inverse.entryPoint == 0) { invertedKeys.push(currencyKey); } inverse.entryPoint = entryPoint; inverse.upperLimit = upperLimit; inverse.lowerLimit = lowerLimit; if (freezeAtUpperLimit || freezeAtLowerLimit) { inverse.frozenAtUpperLimit = freezeAtUpperLimit; inverse.frozenAtLowerLimit = freezeAtLowerLimit; uint roundId = _getCurrentRoundId(currencyKey); roundFrozen[currencyKey] = roundId; emit InversePriceFrozen(currencyKey, freezeAtUpperLimit ? upperLimit : lowerLimit, roundId, msg.sender); inverse.frozenAtUpperLimit = false; inverse.frozenAtLowerLimit = false; roundFrozen[currencyKey] = 0; } if (rate > 0) { exchanger().setLastExchangeRateForPynth(currencyKey, rate); } emit InversePriceConfigured(currencyKey, entryPoint, upperLimit, lowerLimit); } function setInversePricing( bytes32 currencyKey, uint entryPoint, uint upperLimit, uint lowerLimit, bool freezeAtUpperLimit, bool freezeAtLowerLimit ) external onlyOwner { require(lowerLimit > 0, "lowerLimit must be above 0"); require(upperLimit > entryPoint, "upperLimit must be above the entryPoint"); require(upperLimit < entryPoint.mul(2), "upperLimit must be less than double entryPoint"); require(lowerLimit < entryPoint, "lowerLimit must be below the entryPoint"); require(!(freezeAtUpperLimit && freezeAtLowerLimit), "Cannot freeze at both limits"); InversePricing storage inverse = inversePricing[currencyKey]; if (inverse.entryPoint == 0) { invertedKeys.push(currencyKey); } inverse.entryPoint = entryPoint; inverse.upperLimit = upperLimit; inverse.lowerLimit = lowerLimit; if (freezeAtUpperLimit || freezeAtLowerLimit) { inverse.frozenAtUpperLimit = freezeAtUpperLimit; inverse.frozenAtLowerLimit = freezeAtLowerLimit; uint roundId = _getCurrentRoundId(currencyKey); roundFrozen[currencyKey] = roundId; emit InversePriceFrozen(currencyKey, freezeAtUpperLimit ? upperLimit : lowerLimit, roundId, msg.sender); inverse.frozenAtUpperLimit = false; inverse.frozenAtLowerLimit = false; roundFrozen[currencyKey] = 0; } if (rate > 0) { exchanger().setLastExchangeRateForPynth(currencyKey, rate); } emit InversePriceConfigured(currencyKey, entryPoint, upperLimit, lowerLimit); } } else { uint rate = _getRate(currencyKey); function setInversePricing( bytes32 currencyKey, uint entryPoint, uint upperLimit, uint lowerLimit, bool freezeAtUpperLimit, bool freezeAtLowerLimit ) external onlyOwner { require(lowerLimit > 0, "lowerLimit must be above 0"); require(upperLimit > entryPoint, "upperLimit must be above the entryPoint"); require(upperLimit < entryPoint.mul(2), "upperLimit must be less than double entryPoint"); require(lowerLimit < entryPoint, "lowerLimit must be below the entryPoint"); require(!(freezeAtUpperLimit && freezeAtLowerLimit), "Cannot freeze at both limits"); InversePricing storage inverse = inversePricing[currencyKey]; if (inverse.entryPoint == 0) { invertedKeys.push(currencyKey); } inverse.entryPoint = entryPoint; inverse.upperLimit = upperLimit; inverse.lowerLimit = lowerLimit; if (freezeAtUpperLimit || freezeAtLowerLimit) { inverse.frozenAtUpperLimit = freezeAtUpperLimit; inverse.frozenAtLowerLimit = freezeAtLowerLimit; uint roundId = _getCurrentRoundId(currencyKey); roundFrozen[currencyKey] = roundId; emit InversePriceFrozen(currencyKey, freezeAtUpperLimit ? upperLimit : lowerLimit, roundId, msg.sender); inverse.frozenAtUpperLimit = false; inverse.frozenAtLowerLimit = false; roundFrozen[currencyKey] = 0; } if (rate > 0) { exchanger().setLastExchangeRateForPynth(currencyKey, rate); } emit InversePriceConfigured(currencyKey, entryPoint, upperLimit, lowerLimit); } function removeInversePricing(bytes32 currencyKey) external onlyOwner { require(inversePricing[currencyKey].entryPoint > 0, "No inverted price exists"); delete inversePricing[currencyKey]; bool wasRemoved = removeFromArray(currencyKey, invertedKeys); if (wasRemoved) { emit InversePriceConfigured(currencyKey, 0, 0, 0); } } function removeInversePricing(bytes32 currencyKey) external onlyOwner { require(inversePricing[currencyKey].entryPoint > 0, "No inverted price exists"); delete inversePricing[currencyKey]; bool wasRemoved = removeFromArray(currencyKey, invertedKeys); if (wasRemoved) { emit InversePriceConfigured(currencyKey, 0, 0, 0); } } function addAggregator(bytes32 currencyKey, address aggregatorAddress) external onlyOwner { AggregatorV2V3Interface aggregator = AggregatorV2V3Interface(aggregatorAddress); require(aggregator.latestRound() >= 0, "Given Aggregator is invalid"); uint8 decimals = aggregator.decimals(); require(decimals <= 18, "Aggregator decimals should be lower or equal to 18"); if (address(aggregators[currencyKey]) == address(0)) { aggregatorKeys.push(currencyKey); } aggregators[currencyKey] = aggregator; currencyKeyDecimals[currencyKey] = decimals; emit AggregatorAdded(currencyKey, address(aggregator)); } function addAggregator(bytes32 currencyKey, address aggregatorAddress) external onlyOwner { AggregatorV2V3Interface aggregator = AggregatorV2V3Interface(aggregatorAddress); require(aggregator.latestRound() >= 0, "Given Aggregator is invalid"); uint8 decimals = aggregator.decimals(); require(decimals <= 18, "Aggregator decimals should be lower or equal to 18"); if (address(aggregators[currencyKey]) == address(0)) { aggregatorKeys.push(currencyKey); } aggregators[currencyKey] = aggregator; currencyKeyDecimals[currencyKey] = decimals; emit AggregatorAdded(currencyKey, address(aggregator)); } function removeAggregator(bytes32 currencyKey) external onlyOwner { address aggregator = address(aggregators[currencyKey]); require(aggregator != address(0), "No aggregator exists for key"); delete aggregators[currencyKey]; delete currencyKeyDecimals[currencyKey]; bool wasRemoved = removeFromArray(currencyKey, aggregatorKeys); if (wasRemoved) { emit AggregatorRemoved(currencyKey, aggregator); } } function removeAggregator(bytes32 currencyKey) external onlyOwner { address aggregator = address(aggregators[currencyKey]); require(aggregator != address(0), "No aggregator exists for key"); delete aggregators[currencyKey]; delete currencyKeyDecimals[currencyKey]; bool wasRemoved = removeFromArray(currencyKey, aggregatorKeys); if (wasRemoved) { emit AggregatorRemoved(currencyKey, aggregator); } } function freezeRate(bytes32 currencyKey) external { InversePricing storage inverse = inversePricing[currencyKey]; require(inverse.entryPoint > 0, "Cannot freeze non-inverse rate"); require(!inverse.frozenAtUpperLimit && !inverse.frozenAtLowerLimit, "The rate is already frozen"); uint rate = _getRate(currencyKey); if (rate > 0 && (rate >= inverse.upperLimit || rate <= inverse.lowerLimit)) { inverse.frozenAtUpperLimit = (rate == inverse.upperLimit); inverse.frozenAtLowerLimit = (rate == inverse.lowerLimit); uint currentRoundId = _getCurrentRoundId(currencyKey); roundFrozen[currencyKey] = currentRoundId; emit InversePriceFrozen(currencyKey, rate, currentRoundId, msg.sender); revert("Rate within bounds"); } } function freezeRate(bytes32 currencyKey) external { InversePricing storage inverse = inversePricing[currencyKey]; require(inverse.entryPoint > 0, "Cannot freeze non-inverse rate"); require(!inverse.frozenAtUpperLimit && !inverse.frozenAtLowerLimit, "The rate is already frozen"); uint rate = _getRate(currencyKey); if (rate > 0 && (rate >= inverse.upperLimit || rate <= inverse.lowerLimit)) { inverse.frozenAtUpperLimit = (rate == inverse.upperLimit); inverse.frozenAtLowerLimit = (rate == inverse.lowerLimit); uint currentRoundId = _getCurrentRoundId(currencyKey); roundFrozen[currencyKey] = currentRoundId; emit InversePriceFrozen(currencyKey, rate, currentRoundId, msg.sender); revert("Rate within bounds"); } } } else { function resolverAddressesRequired() public view returns (bytes32[] memory addresses) { bytes32[] memory existingAddresses = MixinSystemSettings.resolverAddressesRequired(); bytes32[] memory newAddresses = new bytes32[](1); newAddresses[0] = CONTRACT_EXCHANGER; addresses = combineArrays(existingAddresses, newAddresses); } function canFreezeRate(bytes32 currencyKey) external view returns (bool) { InversePricing memory inverse = inversePricing[currencyKey]; if (inverse.entryPoint == 0 || inverse.frozenAtUpperLimit || inverse.frozenAtLowerLimit) { return false; uint rate = _getRate(currencyKey); return (rate > 0 && (rate >= inverse.upperLimit || rate <= inverse.lowerLimit)); } } function canFreezeRate(bytes32 currencyKey) external view returns (bool) { InversePricing memory inverse = inversePricing[currencyKey]; if (inverse.entryPoint == 0 || inverse.frozenAtUpperLimit || inverse.frozenAtLowerLimit) { return false; uint rate = _getRate(currencyKey); return (rate > 0 && (rate >= inverse.upperLimit || rate <= inverse.lowerLimit)); } } } else { function currenciesUsingAggregator(address aggregator) external view returns (bytes32[] memory currencies) { uint count = 0; currencies = new bytes32[](aggregatorKeys.length); for (uint i = 0; i < aggregatorKeys.length; i++) { bytes32 currencyKey = aggregatorKeys[i]; if (address(aggregators[currencyKey]) == aggregator) { currencies[count++] = currencyKey; } } } function currenciesUsingAggregator(address aggregator) external view returns (bytes32[] memory currencies) { uint count = 0; currencies = new bytes32[](aggregatorKeys.length); for (uint i = 0; i < aggregatorKeys.length; i++) { bytes32 currencyKey = aggregatorKeys[i]; if (address(aggregators[currencyKey]) == aggregator) { currencies[count++] = currencyKey; } } } function currenciesUsingAggregator(address aggregator) external view returns (bytes32[] memory currencies) { uint count = 0; currencies = new bytes32[](aggregatorKeys.length); for (uint i = 0; i < aggregatorKeys.length; i++) { bytes32 currencyKey = aggregatorKeys[i]; if (address(aggregators[currencyKey]) == aggregator) { currencies[count++] = currencyKey; } } } function rateStalePeriod() external view returns (uint) { return getRateStalePeriod(); } function aggregatorWarningFlags() external view returns (address) { return getAggregatorWarningFlags(); } function rateAndUpdatedTime(bytes32 currencyKey) external view returns (uint rate, uint time) { RateAndUpdatedTime memory rateAndTime = _getRateAndUpdatedTime(currencyKey); return (rateAndTime.rate, rateAndTime.time); } function getLastRoundIdBeforeElapsedSecs( bytes32 currencyKey, uint startingRoundId, uint startingTimestamp, uint timediff ) external view returns (uint) { uint roundId = startingRoundId; uint nextTimestamp = 0; while (true) { (, nextTimestamp) = _getRateAndTimestampAtRound(currencyKey, roundId + 1); if (nextTimestamp == 0 || nextTimestamp > startingTimestamp + timediff) { return roundId; } roundId++; } return roundId; } function getLastRoundIdBeforeElapsedSecs( bytes32 currencyKey, uint startingRoundId, uint startingTimestamp, uint timediff ) external view returns (uint) { uint roundId = startingRoundId; uint nextTimestamp = 0; while (true) { (, nextTimestamp) = _getRateAndTimestampAtRound(currencyKey, roundId + 1); if (nextTimestamp == 0 || nextTimestamp > startingTimestamp + timediff) { return roundId; } roundId++; } return roundId; } function getLastRoundIdBeforeElapsedSecs( bytes32 currencyKey, uint startingRoundId, uint startingTimestamp, uint timediff ) external view returns (uint) { uint roundId = startingRoundId; uint nextTimestamp = 0; while (true) { (, nextTimestamp) = _getRateAndTimestampAtRound(currencyKey, roundId + 1); if (nextTimestamp == 0 || nextTimestamp > startingTimestamp + timediff) { return roundId; } roundId++; } return roundId; } function getCurrentRoundId(bytes32 currencyKey) external view returns (uint) { return _getCurrentRoundId(currencyKey); } function effectiveValueAtRound( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, uint roundIdForSrc, uint roundIdForDest ) external view returns (uint value) { if (sourceCurrencyKey == destinationCurrencyKey) return sourceAmount; (uint srcRate, ) = _getRateAndTimestampAtRound(sourceCurrencyKey, roundIdForSrc); (uint destRate, ) = _getRateAndTimestampAtRound(destinationCurrencyKey, roundIdForDest); if (destRate == 0) { return 0; } } function effectiveValueAtRound( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, uint roundIdForSrc, uint roundIdForDest ) external view returns (uint value) { if (sourceCurrencyKey == destinationCurrencyKey) return sourceAmount; (uint srcRate, ) = _getRateAndTimestampAtRound(sourceCurrencyKey, roundIdForSrc); (uint destRate, ) = _getRateAndTimestampAtRound(destinationCurrencyKey, roundIdForDest); if (destRate == 0) { return 0; } } value = sourceAmount.multiplyDecimalRound(srcRate).divideDecimalRound(destRate); function rateAndTimestampAtRound(bytes32 currencyKey, uint roundId) external view returns (uint rate, uint time) { return _getRateAndTimestampAtRound(currencyKey, roundId); } function lastRateUpdateTimes(bytes32 currencyKey) external view returns (uint256) { return _getUpdatedTime(currencyKey); } function lastRateUpdateTimesForCurrencies(bytes32[] calldata currencyKeys) external view returns (uint[] memory) { uint[] memory lastUpdateTimes = new uint[](currencyKeys.length); for (uint i = 0; i < currencyKeys.length; i++) { lastUpdateTimes[i] = _getUpdatedTime(currencyKeys[i]); } return lastUpdateTimes; } function lastRateUpdateTimesForCurrencies(bytes32[] calldata currencyKeys) external view returns (uint[] memory) { uint[] memory lastUpdateTimes = new uint[](currencyKeys.length); for (uint i = 0; i < currencyKeys.length; i++) { lastUpdateTimes[i] = _getUpdatedTime(currencyKeys[i]); } return lastUpdateTimes; } function effectiveValue( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey ) external view returns (uint value) { (value, , ) = _effectiveValueAndRates(sourceCurrencyKey, sourceAmount, destinationCurrencyKey); } function effectiveValueAndRates( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey ) external view returns ( uint value, uint sourceRate, uint destinationRate ) { return _effectiveValueAndRates(sourceCurrencyKey, sourceAmount, destinationCurrencyKey); } function rateForCurrency(bytes32 currencyKey) external view returns (uint) { return _getRateAndUpdatedTime(currencyKey).rate; } function ratesAndUpdatedTimeForCurrencyLastNRounds(bytes32 currencyKey, uint numRounds) external view returns (uint[] memory rates, uint[] memory times) { rates = new uint[](numRounds); times = new uint[](numRounds); uint roundId = _getCurrentRoundId(currencyKey); for (uint i = 0; i < numRounds; i++) { (rates[i], times[i]) = _getRateAndTimestampAtRound(currencyKey, roundId); if (roundId == 0) { return (rates, times); roundId--; } } } function ratesAndUpdatedTimeForCurrencyLastNRounds(bytes32 currencyKey, uint numRounds) external view returns (uint[] memory rates, uint[] memory times) { rates = new uint[](numRounds); times = new uint[](numRounds); uint roundId = _getCurrentRoundId(currencyKey); for (uint i = 0; i < numRounds; i++) { (rates[i], times[i]) = _getRateAndTimestampAtRound(currencyKey, roundId); if (roundId == 0) { return (rates, times); roundId--; } } } function ratesAndUpdatedTimeForCurrencyLastNRounds(bytes32 currencyKey, uint numRounds) external view returns (uint[] memory rates, uint[] memory times) { rates = new uint[](numRounds); times = new uint[](numRounds); uint roundId = _getCurrentRoundId(currencyKey); for (uint i = 0; i < numRounds; i++) { (rates[i], times[i]) = _getRateAndTimestampAtRound(currencyKey, roundId); if (roundId == 0) { return (rates, times); roundId--; } } } } else { function ratesForCurrencies(bytes32[] calldata currencyKeys) external view returns (uint[] memory) { uint[] memory _localRates = new uint[](currencyKeys.length); for (uint i = 0; i < currencyKeys.length; i++) { _localRates[i] = _getRate(currencyKeys[i]); } return _localRates; } function ratesForCurrencies(bytes32[] calldata currencyKeys) external view returns (uint[] memory) { uint[] memory _localRates = new uint[](currencyKeys.length); for (uint i = 0; i < currencyKeys.length; i++) { _localRates[i] = _getRate(currencyKeys[i]); } return _localRates; } function rateAndInvalid(bytes32 currencyKey) external view returns (uint rate, bool isInvalid) { RateAndUpdatedTime memory rateAndTime = _getRateAndUpdatedTime(currencyKey); if (currencyKey == "pUSD") { return (rateAndTime.rate, false); } return ( rateAndTime.rate, _rateIsStaleWithTime(getRateStalePeriod(), rateAndTime.time) || _rateIsFlagged(currencyKey, FlagsInterface(getAggregatorWarningFlags())) ); } function rateAndInvalid(bytes32 currencyKey) external view returns (uint rate, bool isInvalid) { RateAndUpdatedTime memory rateAndTime = _getRateAndUpdatedTime(currencyKey); if (currencyKey == "pUSD") { return (rateAndTime.rate, false); } return ( rateAndTime.rate, _rateIsStaleWithTime(getRateStalePeriod(), rateAndTime.time) || _rateIsFlagged(currencyKey, FlagsInterface(getAggregatorWarningFlags())) ); } function ratesAndInvalidForCurrencies(bytes32[] calldata currencyKeys) external view returns (uint[] memory rates, bool anyRateInvalid) { rates = new uint[](currencyKeys.length); uint256 _rateStalePeriod = getRateStalePeriod(); bool[] memory flagList = getFlagsForRates(currencyKeys); for (uint i = 0; i < currencyKeys.length; i++) { RateAndUpdatedTime memory rateEntry = _getRateAndUpdatedTime(currencyKeys[i]); rates[i] = rateEntry.rate; if (!anyRateInvalid && currencyKeys[i] != "pUSD") { anyRateInvalid = flagList[i] || _rateIsStaleWithTime(_rateStalePeriod, rateEntry.time); } } } function ratesAndInvalidForCurrencies(bytes32[] calldata currencyKeys) external view returns (uint[] memory rates, bool anyRateInvalid) { rates = new uint[](currencyKeys.length); uint256 _rateStalePeriod = getRateStalePeriod(); bool[] memory flagList = getFlagsForRates(currencyKeys); for (uint i = 0; i < currencyKeys.length; i++) { RateAndUpdatedTime memory rateEntry = _getRateAndUpdatedTime(currencyKeys[i]); rates[i] = rateEntry.rate; if (!anyRateInvalid && currencyKeys[i] != "pUSD") { anyRateInvalid = flagList[i] || _rateIsStaleWithTime(_rateStalePeriod, rateEntry.time); } } } function ratesAndInvalidForCurrencies(bytes32[] calldata currencyKeys) external view returns (uint[] memory rates, bool anyRateInvalid) { rates = new uint[](currencyKeys.length); uint256 _rateStalePeriod = getRateStalePeriod(); bool[] memory flagList = getFlagsForRates(currencyKeys); for (uint i = 0; i < currencyKeys.length; i++) { RateAndUpdatedTime memory rateEntry = _getRateAndUpdatedTime(currencyKeys[i]); rates[i] = rateEntry.rate; if (!anyRateInvalid && currencyKeys[i] != "pUSD") { anyRateInvalid = flagList[i] || _rateIsStaleWithTime(_rateStalePeriod, rateEntry.time); } } } function rateIsStale(bytes32 currencyKey) external view returns (bool) { return _rateIsStale(currencyKey, getRateStalePeriod()); } function rateIsFrozen(bytes32 currencyKey) external view returns (bool) { return _rateIsFrozen(currencyKey); } function rateIsInvalid(bytes32 currencyKey) external view returns (bool) { return _rateIsStale(currencyKey, getRateStalePeriod()) || _rateIsFlagged(currencyKey, FlagsInterface(getAggregatorWarningFlags())); } function rateIsFlagged(bytes32 currencyKey) external view returns (bool) { return _rateIsFlagged(currencyKey, FlagsInterface(getAggregatorWarningFlags())); } function anyRateIsInvalid(bytes32[] calldata currencyKeys) external view returns (bool) { uint256 _rateStalePeriod = getRateStalePeriod(); bool[] memory flagList = getFlagsForRates(currencyKeys); for (uint i = 0; i < currencyKeys.length; i++) { if (flagList[i] || _rateIsStale(currencyKeys[i], _rateStalePeriod)) { return true; } } return false; } function anyRateIsInvalid(bytes32[] calldata currencyKeys) external view returns (bool) { uint256 _rateStalePeriod = getRateStalePeriod(); bool[] memory flagList = getFlagsForRates(currencyKeys); for (uint i = 0; i < currencyKeys.length; i++) { if (flagList[i] || _rateIsStale(currencyKeys[i], _rateStalePeriod)) { return true; } } return false; } function anyRateIsInvalid(bytes32[] calldata currencyKeys) external view returns (bool) { uint256 _rateStalePeriod = getRateStalePeriod(); bool[] memory flagList = getFlagsForRates(currencyKeys); for (uint i = 0; i < currencyKeys.length; i++) { if (flagList[i] || _rateIsStale(currencyKeys[i], _rateStalePeriod)) { return true; } } return false; } function exchanger() internal view returns (IExchanger) { return IExchanger(requireAndGetAddress(CONTRACT_EXCHANGER)); } function getFlagsForRates(bytes32[] memory currencyKeys) internal view returns (bool[] memory flagList) { FlagsInterface _flags = FlagsInterface(getAggregatorWarningFlags()); if (_flags != FlagsInterface(0)) { address[] memory _aggregators = new address[](currencyKeys.length); for (uint i = 0; i < currencyKeys.length; i++) { _aggregators[i] = address(aggregators[currencyKeys[i]]); } flagList = _flags.getFlags(_aggregators); flagList = new bool[](currencyKeys.length); } } function getFlagsForRates(bytes32[] memory currencyKeys) internal view returns (bool[] memory flagList) { FlagsInterface _flags = FlagsInterface(getAggregatorWarningFlags()); if (_flags != FlagsInterface(0)) { address[] memory _aggregators = new address[](currencyKeys.length); for (uint i = 0; i < currencyKeys.length; i++) { _aggregators[i] = address(aggregators[currencyKeys[i]]); } flagList = _flags.getFlags(_aggregators); flagList = new bool[](currencyKeys.length); } } function getFlagsForRates(bytes32[] memory currencyKeys) internal view returns (bool[] memory flagList) { FlagsInterface _flags = FlagsInterface(getAggregatorWarningFlags()); if (_flags != FlagsInterface(0)) { address[] memory _aggregators = new address[](currencyKeys.length); for (uint i = 0; i < currencyKeys.length; i++) { _aggregators[i] = address(aggregators[currencyKeys[i]]); } flagList = _flags.getFlags(_aggregators); flagList = new bool[](currencyKeys.length); } } } else { function _setRate( bytes32 currencyKey, uint256 rate, uint256 time ) internal { currentRoundForRate[currencyKey]++; _rates[currencyKey][currentRoundForRate[currencyKey]] = RateAndUpdatedTime({ rate: uint216(rate), time: uint40(time) }); } function _setRate( bytes32 currencyKey, uint256 rate, uint256 time ) internal { currentRoundForRate[currencyKey]++; _rates[currencyKey][currentRoundForRate[currencyKey]] = RateAndUpdatedTime({ rate: uint216(rate), time: uint40(time) }); } function internalUpdateRates( bytes32[] memory currencyKeys, uint[] memory newRates, uint timeSent ) internal returns (bool) { require(currencyKeys.length == newRates.length, "Currency key array length must match rates array length."); require(timeSent < (now + ORACLE_FUTURE_LIMIT), "Time is too far into the future"); for (uint i = 0; i < currencyKeys.length; i++) { bytes32 currencyKey = currencyKeys[i]; require(newRates[i] != 0, "Zero is not a valid rate, please call deleteRate instead."); require(currencyKey != "pUSD", "Rate of pUSD cannot be updated, it's always UNIT."); if (timeSent < _getUpdatedTime(currencyKey)) { continue; } } emit RatesUpdated(currencyKeys, newRates); return true; } function internalUpdateRates( bytes32[] memory currencyKeys, uint[] memory newRates, uint timeSent ) internal returns (bool) { require(currencyKeys.length == newRates.length, "Currency key array length must match rates array length."); require(timeSent < (now + ORACLE_FUTURE_LIMIT), "Time is too far into the future"); for (uint i = 0; i < currencyKeys.length; i++) { bytes32 currencyKey = currencyKeys[i]; require(newRates[i] != 0, "Zero is not a valid rate, please call deleteRate instead."); require(currencyKey != "pUSD", "Rate of pUSD cannot be updated, it's always UNIT."); if (timeSent < _getUpdatedTime(currencyKey)) { continue; } } emit RatesUpdated(currencyKeys, newRates); return true; } function internalUpdateRates( bytes32[] memory currencyKeys, uint[] memory newRates, uint timeSent ) internal returns (bool) { require(currencyKeys.length == newRates.length, "Currency key array length must match rates array length."); require(timeSent < (now + ORACLE_FUTURE_LIMIT), "Time is too far into the future"); for (uint i = 0; i < currencyKeys.length; i++) { bytes32 currencyKey = currencyKeys[i]; require(newRates[i] != 0, "Zero is not a valid rate, please call deleteRate instead."); require(currencyKey != "pUSD", "Rate of pUSD cannot be updated, it's always UNIT."); if (timeSent < _getUpdatedTime(currencyKey)) { continue; } } emit RatesUpdated(currencyKeys, newRates); return true; } _setRate(currencyKey, newRates[i], timeSent); function removeFromArray(bytes32 entry, bytes32[] storage array) internal returns (bool) { for (uint i = 0; i < array.length; i++) { if (array[i] == entry) { delete array[i]; array[i] = array[array.length - 1]; array.length--; return true; } } return false; } function removeFromArray(bytes32 entry, bytes32[] storage array) internal returns (bool) { for (uint i = 0; i < array.length; i++) { if (array[i] == entry) { delete array[i]; array[i] = array[array.length - 1]; array.length--; return true; } } return false; } function removeFromArray(bytes32 entry, bytes32[] storage array) internal returns (bool) { for (uint i = 0; i < array.length; i++) { if (array[i] == entry) { delete array[i]; array[i] = array[array.length - 1]; array.length--; return true; } } return false; } function _rateOrInverted( bytes32 currencyKey, uint rate, uint roundId ) internal view returns (uint newRate) { InversePricing memory inverse = inversePricing[currencyKey]; if (inverse.entryPoint == 0 || rate == 0) { return rate; } newRate = rate; if (roundId >= roundWhenRateFrozen && inverse.frozenAtUpperLimit) { newRate = inverse.upperLimit; newRate = inverse.lowerLimit; uint doubleEntryPoint = inverse.entryPoint.mul(2); if (doubleEntryPoint <= rate) { newRate = 0; newRate = doubleEntryPoint.sub(rate); } if (newRate >= inverse.upperLimit) { newRate = inverse.upperLimit; newRate = inverse.lowerLimit; } } } function _rateOrInverted( bytes32 currencyKey, uint rate, uint roundId ) internal view returns (uint newRate) { InversePricing memory inverse = inversePricing[currencyKey]; if (inverse.entryPoint == 0 || rate == 0) { return rate; } newRate = rate; if (roundId >= roundWhenRateFrozen && inverse.frozenAtUpperLimit) { newRate = inverse.upperLimit; newRate = inverse.lowerLimit; uint doubleEntryPoint = inverse.entryPoint.mul(2); if (doubleEntryPoint <= rate) { newRate = 0; newRate = doubleEntryPoint.sub(rate); } if (newRate >= inverse.upperLimit) { newRate = inverse.upperLimit; newRate = inverse.lowerLimit; } } } uint roundWhenRateFrozen = roundFrozen[currencyKey]; function _rateOrInverted( bytes32 currencyKey, uint rate, uint roundId ) internal view returns (uint newRate) { InversePricing memory inverse = inversePricing[currencyKey]; if (inverse.entryPoint == 0 || rate == 0) { return rate; } newRate = rate; if (roundId >= roundWhenRateFrozen && inverse.frozenAtUpperLimit) { newRate = inverse.upperLimit; newRate = inverse.lowerLimit; uint doubleEntryPoint = inverse.entryPoint.mul(2); if (doubleEntryPoint <= rate) { newRate = 0; newRate = doubleEntryPoint.sub(rate); } if (newRate >= inverse.upperLimit) { newRate = inverse.upperLimit; newRate = inverse.lowerLimit; } } } } else if (roundId >= roundWhenRateFrozen && inverse.frozenAtLowerLimit) { } else { function _rateOrInverted( bytes32 currencyKey, uint rate, uint roundId ) internal view returns (uint newRate) { InversePricing memory inverse = inversePricing[currencyKey]; if (inverse.entryPoint == 0 || rate == 0) { return rate; } newRate = rate; if (roundId >= roundWhenRateFrozen && inverse.frozenAtUpperLimit) { newRate = inverse.upperLimit; newRate = inverse.lowerLimit; uint doubleEntryPoint = inverse.entryPoint.mul(2); if (doubleEntryPoint <= rate) { newRate = 0; newRate = doubleEntryPoint.sub(rate); } if (newRate >= inverse.upperLimit) { newRate = inverse.upperLimit; newRate = inverse.lowerLimit; } } } } else { function _rateOrInverted( bytes32 currencyKey, uint rate, uint roundId ) internal view returns (uint newRate) { InversePricing memory inverse = inversePricing[currencyKey]; if (inverse.entryPoint == 0 || rate == 0) { return rate; } newRate = rate; if (roundId >= roundWhenRateFrozen && inverse.frozenAtUpperLimit) { newRate = inverse.upperLimit; newRate = inverse.lowerLimit; uint doubleEntryPoint = inverse.entryPoint.mul(2); if (doubleEntryPoint <= rate) { newRate = 0; newRate = doubleEntryPoint.sub(rate); } if (newRate >= inverse.upperLimit) { newRate = inverse.upperLimit; newRate = inverse.lowerLimit; } } } } else if (newRate <= inverse.lowerLimit) { function _formatAggregatorAnswer(bytes32 currencyKey, int256 rate) internal view returns (uint) { require(rate >= 0, "Negative rate not supported"); if (currencyKeyDecimals[currencyKey] > 0) { uint multiplier = 10**uint(SafeMath.sub(18, currencyKeyDecimals[currencyKey])); return uint(uint(rate).mul(multiplier)); } return uint(rate); } function _formatAggregatorAnswer(bytes32 currencyKey, int256 rate) internal view returns (uint) { require(rate >= 0, "Negative rate not supported"); if (currencyKeyDecimals[currencyKey] > 0) { uint multiplier = 10**uint(SafeMath.sub(18, currencyKeyDecimals[currencyKey])); return uint(uint(rate).mul(multiplier)); } return uint(rate); } function _getRateAndUpdatedTime(bytes32 currencyKey) internal view returns (RateAndUpdatedTime memory) { if (currencyByExternal[currencyKey]) { require(externalRateAggregator != address(0), "External price aggregator is not set yet"); IExternalRateAggregator _externalRateAggregator = IExternalRateAggregator(externalRateAggregator); (uint rate, uint time) = _externalRateAggregator.getRateAndUpdatedTime(currencyKey); } AggregatorV2V3Interface aggregator = aggregators[currencyKey]; if (aggregator != AggregatorV2V3Interface(0)) { bytes memory payload = abi.encodeWithSignature("latestRoundData()"); (bool success, bytes memory returnData) = address(aggregator).staticcall(payload); if (success) { (uint80 roundId, int256 answer, , uint256 updatedAt, ) = abi.decode(returnData, (uint80, int256, uint256, uint256, uint80)); return RateAndUpdatedTime({ rate: uint216(_rateOrInverted(currencyKey, _formatAggregatorAnswer(currencyKey, answer), roundId)), time: uint40(updatedAt) }); } uint roundId = currentRoundForRate[currencyKey]; RateAndUpdatedTime memory entry = _rates[currencyKey][roundId]; } } function _getRateAndUpdatedTime(bytes32 currencyKey) internal view returns (RateAndUpdatedTime memory) { if (currencyByExternal[currencyKey]) { require(externalRateAggregator != address(0), "External price aggregator is not set yet"); IExternalRateAggregator _externalRateAggregator = IExternalRateAggregator(externalRateAggregator); (uint rate, uint time) = _externalRateAggregator.getRateAndUpdatedTime(currencyKey); } AggregatorV2V3Interface aggregator = aggregators[currencyKey]; if (aggregator != AggregatorV2V3Interface(0)) { bytes memory payload = abi.encodeWithSignature("latestRoundData()"); (bool success, bytes memory returnData) = address(aggregator).staticcall(payload); if (success) { (uint80 roundId, int256 answer, , uint256 updatedAt, ) = abi.decode(returnData, (uint80, int256, uint256, uint256, uint80)); return RateAndUpdatedTime({ rate: uint216(_rateOrInverted(currencyKey, _formatAggregatorAnswer(currencyKey, answer), roundId)), time: uint40(updatedAt) }); } uint roundId = currentRoundForRate[currencyKey]; RateAndUpdatedTime memory entry = _rates[currencyKey][roundId]; } } return RateAndUpdatedTime({rate: uint216(rate), time: uint40(time)}); function _getRateAndUpdatedTime(bytes32 currencyKey) internal view returns (RateAndUpdatedTime memory) { if (currencyByExternal[currencyKey]) { require(externalRateAggregator != address(0), "External price aggregator is not set yet"); IExternalRateAggregator _externalRateAggregator = IExternalRateAggregator(externalRateAggregator); (uint rate, uint time) = _externalRateAggregator.getRateAndUpdatedTime(currencyKey); } AggregatorV2V3Interface aggregator = aggregators[currencyKey]; if (aggregator != AggregatorV2V3Interface(0)) { bytes memory payload = abi.encodeWithSignature("latestRoundData()"); (bool success, bytes memory returnData) = address(aggregator).staticcall(payload); if (success) { (uint80 roundId, int256 answer, , uint256 updatedAt, ) = abi.decode(returnData, (uint80, int256, uint256, uint256, uint80)); return RateAndUpdatedTime({ rate: uint216(_rateOrInverted(currencyKey, _formatAggregatorAnswer(currencyKey, answer), roundId)), time: uint40(updatedAt) }); } uint roundId = currentRoundForRate[currencyKey]; RateAndUpdatedTime memory entry = _rates[currencyKey][roundId]; } } function _getRateAndUpdatedTime(bytes32 currencyKey) internal view returns (RateAndUpdatedTime memory) { if (currencyByExternal[currencyKey]) { require(externalRateAggregator != address(0), "External price aggregator is not set yet"); IExternalRateAggregator _externalRateAggregator = IExternalRateAggregator(externalRateAggregator); (uint rate, uint time) = _externalRateAggregator.getRateAndUpdatedTime(currencyKey); } AggregatorV2V3Interface aggregator = aggregators[currencyKey]; if (aggregator != AggregatorV2V3Interface(0)) { bytes memory payload = abi.encodeWithSignature("latestRoundData()"); (bool success, bytes memory returnData) = address(aggregator).staticcall(payload); if (success) { (uint80 roundId, int256 answer, , uint256 updatedAt, ) = abi.decode(returnData, (uint80, int256, uint256, uint256, uint80)); return RateAndUpdatedTime({ rate: uint216(_rateOrInverted(currencyKey, _formatAggregatorAnswer(currencyKey, answer), roundId)), time: uint40(updatedAt) }); } uint roundId = currentRoundForRate[currencyKey]; RateAndUpdatedTime memory entry = _rates[currencyKey][roundId]; } } function _getRateAndUpdatedTime(bytes32 currencyKey) internal view returns (RateAndUpdatedTime memory) { if (currencyByExternal[currencyKey]) { require(externalRateAggregator != address(0), "External price aggregator is not set yet"); IExternalRateAggregator _externalRateAggregator = IExternalRateAggregator(externalRateAggregator); (uint rate, uint time) = _externalRateAggregator.getRateAndUpdatedTime(currencyKey); } AggregatorV2V3Interface aggregator = aggregators[currencyKey]; if (aggregator != AggregatorV2V3Interface(0)) { bytes memory payload = abi.encodeWithSignature("latestRoundData()"); (bool success, bytes memory returnData) = address(aggregator).staticcall(payload); if (success) { (uint80 roundId, int256 answer, , uint256 updatedAt, ) = abi.decode(returnData, (uint80, int256, uint256, uint256, uint80)); return RateAndUpdatedTime({ rate: uint216(_rateOrInverted(currencyKey, _formatAggregatorAnswer(currencyKey, answer), roundId)), time: uint40(updatedAt) }); } uint roundId = currentRoundForRate[currencyKey]; RateAndUpdatedTime memory entry = _rates[currencyKey][roundId]; } } } else { return RateAndUpdatedTime({rate: uint216(_rateOrInverted(currencyKey, entry.rate, roundId)), time: entry.time}); function _getCurrentRoundId(bytes32 currencyKey) internal view returns (uint) { AggregatorV2V3Interface aggregator = aggregators[currencyKey]; if (aggregator != AggregatorV2V3Interface(0)) { return aggregator.latestRound(); return currentRoundForRate[currencyKey]; } } function _getCurrentRoundId(bytes32 currencyKey) internal view returns (uint) { AggregatorV2V3Interface aggregator = aggregators[currencyKey]; if (aggregator != AggregatorV2V3Interface(0)) { return aggregator.latestRound(); return currentRoundForRate[currencyKey]; } } } else { function _getRateAndTimestampAtRound(bytes32 currencyKey, uint roundId) internal view returns (uint rate, uint time) { AggregatorV2V3Interface aggregator = aggregators[currencyKey]; if (aggregator != AggregatorV2V3Interface(0)) { bytes memory payload = abi.encodeWithSignature("getRoundData(uint80)", roundId); (bool success, bytes memory returnData) = address(aggregator).staticcall(payload); if (success) { (, int256 answer, , uint256 updatedAt, ) = abi.decode(returnData, (uint80, int256, uint256, uint256, uint80)); return (_rateOrInverted(currencyKey, _formatAggregatorAnswer(currencyKey, answer), roundId), updatedAt); } RateAndUpdatedTime memory update = _rates[currencyKey][roundId]; return (_rateOrInverted(currencyKey, update.rate, roundId), update.time); } } function _getRateAndTimestampAtRound(bytes32 currencyKey, uint roundId) internal view returns (uint rate, uint time) { AggregatorV2V3Interface aggregator = aggregators[currencyKey]; if (aggregator != AggregatorV2V3Interface(0)) { bytes memory payload = abi.encodeWithSignature("getRoundData(uint80)", roundId); (bool success, bytes memory returnData) = address(aggregator).staticcall(payload); if (success) { (, int256 answer, , uint256 updatedAt, ) = abi.decode(returnData, (uint80, int256, uint256, uint256, uint80)); return (_rateOrInverted(currencyKey, _formatAggregatorAnswer(currencyKey, answer), roundId), updatedAt); } RateAndUpdatedTime memory update = _rates[currencyKey][roundId]; return (_rateOrInverted(currencyKey, update.rate, roundId), update.time); } } function _getRateAndTimestampAtRound(bytes32 currencyKey, uint roundId) internal view returns (uint rate, uint time) { AggregatorV2V3Interface aggregator = aggregators[currencyKey]; if (aggregator != AggregatorV2V3Interface(0)) { bytes memory payload = abi.encodeWithSignature("getRoundData(uint80)", roundId); (bool success, bytes memory returnData) = address(aggregator).staticcall(payload); if (success) { (, int256 answer, , uint256 updatedAt, ) = abi.decode(returnData, (uint80, int256, uint256, uint256, uint80)); return (_rateOrInverted(currencyKey, _formatAggregatorAnswer(currencyKey, answer), roundId), updatedAt); } RateAndUpdatedTime memory update = _rates[currencyKey][roundId]; return (_rateOrInverted(currencyKey, update.rate, roundId), update.time); } } } else { function _getRate(bytes32 currencyKey) internal view returns (uint256) { return _getRateAndUpdatedTime(currencyKey).rate; } function _getUpdatedTime(bytes32 currencyKey) internal view returns (uint256) { return _getRateAndUpdatedTime(currencyKey).time; } function _effectiveValueAndRates( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey ) internal view returns ( uint value, uint sourceRate, uint destinationRate ) { sourceRate = _getRate(sourceCurrencyKey); if (sourceCurrencyKey == destinationCurrencyKey) { destinationRate = sourceRate; value = sourceAmount; destinationRate = _getRate(destinationCurrencyKey); if (destinationRate > 0) { value = sourceAmount.multiplyDecimalRound(sourceRate).divideDecimalRound(destinationRate); } } } function _effectiveValueAndRates( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey ) internal view returns ( uint value, uint sourceRate, uint destinationRate ) { sourceRate = _getRate(sourceCurrencyKey); if (sourceCurrencyKey == destinationCurrencyKey) { destinationRate = sourceRate; value = sourceAmount; destinationRate = _getRate(destinationCurrencyKey); if (destinationRate > 0) { value = sourceAmount.multiplyDecimalRound(sourceRate).divideDecimalRound(destinationRate); } } } } else { function _effectiveValueAndRates( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey ) internal view returns ( uint value, uint sourceRate, uint destinationRate ) { sourceRate = _getRate(sourceCurrencyKey); if (sourceCurrencyKey == destinationCurrencyKey) { destinationRate = sourceRate; value = sourceAmount; destinationRate = _getRate(destinationCurrencyKey); if (destinationRate > 0) { value = sourceAmount.multiplyDecimalRound(sourceRate).divideDecimalRound(destinationRate); } } } function _rateIsStale(bytes32 currencyKey, uint _rateStalePeriod) internal view returns (bool) { if (currencyKey == "pUSD") return false; return _rateIsStaleWithTime(_rateStalePeriod, _getUpdatedTime(currencyKey)); } function _rateIsStaleWithTime(uint _rateStalePeriod, uint _time) internal view returns (bool) { return _time.add(_rateStalePeriod) < now; } function _rateIsFrozen(bytes32 currencyKey) internal view returns (bool) { InversePricing memory inverse = inversePricing[currencyKey]; return inverse.frozenAtUpperLimit || inverse.frozenAtLowerLimit; } function _rateIsFlagged(bytes32 currencyKey, FlagsInterface flags) internal view returns (bool) { if (currencyKey == "pUSD") return false; address aggregator = address(aggregators[currencyKey]); if (aggregator == address(0) || flags == FlagsInterface(0)) { return false; } return flags.getFlag(aggregator); } function _rateIsFlagged(bytes32 currencyKey, FlagsInterface flags) internal view returns (bool) { if (currencyKey == "pUSD") return false; address aggregator = address(aggregators[currencyKey]); if (aggregator == address(0) || flags == FlagsInterface(0)) { return false; } return flags.getFlag(aggregator); } modifier onlyOracle { _onlyOracle(); _; } function _onlyOracle() internal view { require(msg.sender == oracle, "Only the oracle can perform this action"); } event OracleUpdated(address newOracle); event RatesUpdated(bytes32[] currencyKeys, uint[] newRates); event RateDeleted(bytes32 currencyKey); event InversePriceConfigured(bytes32 currencyKey, uint entryPoint, uint upperLimit, uint lowerLimit); event InversePriceFrozen(bytes32 currencyKey, uint rate, uint roundId, address initiator); event AggregatorAdded(bytes32 currencyKey, address aggregator); event AggregatorRemoved(bytes32 currencyKey, address aggregator); }
12,202,693
[ 1, 4528, 30, 8532, 18, 457, 77, 18, 926, 1359, 19, 16351, 87, 19, 3168, 19, 16351, 87, 19, 338, 343, 11455, 815, 18903, 17544, 471, 1089, 4124, 4041, 635, 5462, 981, 16, 425, 18, 75, 18, 296, 3194, 45, 2187, 578, 296, 84, 3378, 40, 11, 1021, 1758, 434, 326, 20865, 1492, 27351, 4993, 4533, 358, 333, 6835, 3416, 12839, 1235, 20865, 13884, 716, 4746, 1368, 31765, 4377, 3062, 987, 434, 20762, 1311, 364, 26375, 6532, 2256, 486, 1699, 326, 20865, 358, 4879, 4124, 1281, 9271, 5104, 1368, 326, 3563, 2353, 333, 5381, 18, 422, 1432, 3492, 13915, 916, 422, 1432, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 16351, 18903, 20836, 353, 14223, 11748, 16, 490, 10131, 3163, 2628, 16, 467, 11688, 20836, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 31, 203, 565, 1450, 14060, 5749, 10477, 364, 2254, 31, 203, 203, 565, 2874, 12, 3890, 1578, 516, 2874, 12, 11890, 516, 13025, 1876, 7381, 950, 3719, 3238, 389, 24285, 31, 203, 203, 565, 1758, 1071, 20865, 31, 203, 203, 565, 1758, 1071, 3903, 4727, 17711, 31, 203, 203, 565, 2874, 12, 3890, 1578, 516, 1426, 13, 1071, 5462, 858, 6841, 31, 203, 203, 565, 2874, 12, 3890, 1578, 516, 10594, 639, 58, 22, 58, 23, 1358, 13, 1071, 4377, 3062, 31, 203, 203, 565, 2874, 12, 3890, 1578, 516, 2254, 28, 13, 1071, 5462, 653, 31809, 31, 203, 203, 565, 1731, 1578, 8526, 1071, 20762, 2396, 31, 203, 203, 565, 2254, 3238, 5381, 4869, 2226, 900, 67, 42, 1693, 4830, 67, 8283, 273, 1728, 6824, 31, 203, 203, 565, 2874, 12, 3890, 1578, 516, 657, 2476, 52, 1512, 310, 13, 1071, 8322, 52, 1512, 310, 31, 203, 203, 565, 1731, 1578, 8526, 1071, 18150, 2396, 31, 203, 203, 565, 2874, 12, 3890, 1578, 516, 2254, 13, 1071, 783, 11066, 1290, 4727, 31, 203, 203, 565, 2874, 12, 3890, 1578, 516, 2254, 13, 1071, 3643, 42, 9808, 31, 203, 203, 565, 1731, 1578, 3238, 5381, 8020, 2849, 1268, 67, 2294, 1792, 1258, 3101, 273, 315, 424, 343, 11455, 14432, 203, 203, 203, 565, 3885, 12, 203, 3639, 1758, 389, 8443, 16, 203, 3639, 1758, 389, 280, 16066, 16, 203, 3639, 1758, 2 ]
./full_match/41/0x94E5d9333F5Db0eEf59CDd8B1B2616008E4E9c50/sources/contracts/BunyERC6551Account.sol
receive native chain erc20 tokens ie. TLOS
function deposit() public payable { require(msg.value > 0, "Deposit amount must be greater than 0."); depositCount++; deposits[depositCount] = Deposit({ }); emit NewDeposit(msg.sender, msg.value, block.timestamp); }
16,376,590
[ 1, 18149, 6448, 2687, 6445, 71, 3462, 2430, 9228, 18, 399, 1502, 55, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 443, 1724, 1435, 1071, 8843, 429, 288, 203, 3639, 2583, 12, 3576, 18, 1132, 405, 374, 16, 315, 758, 1724, 3844, 1297, 506, 6802, 2353, 374, 1199, 1769, 203, 5411, 443, 1724, 1380, 9904, 31, 7010, 5411, 443, 917, 1282, 63, 323, 1724, 1380, 65, 273, 4019, 538, 305, 12590, 203, 3639, 15549, 203, 3639, 3626, 1166, 758, 1724, 12, 3576, 18, 15330, 16, 1234, 18, 1132, 16, 1203, 18, 5508, 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 ]
./full_match/73799/0xC4cBa76beED0148769B3f7DFEeA9A54687d58c2b/sources/contracts/libraries/LibVoting.sol
There can not be voting without some session
function _startSession(bytes32 votingID, bytes32 matchResult) internal { if (_getStorage().votingIDToVoting[votingID].sessionIDs.length == 0) { _getStorage().votingIDs.push(votingID); } Voting storage voting = _getStorage().votingIDToVoting[votingID]; bytes32 sessionID = _getSessionID(votingID, matchResult); VotingSession storage session = voting.sessionIDToSession[sessionID]; session.matchResult = matchResult; session.startTimestamp = block.timestamp; session.status = Status.Started; voting.sessionIDs.push(sessionID); }
16,363,518
[ 1, 9828, 848, 486, 506, 331, 17128, 2887, 2690, 1339, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 1937, 2157, 12, 3890, 1578, 331, 17128, 734, 16, 1731, 1578, 845, 1253, 13, 2713, 288, 203, 3639, 309, 261, 67, 588, 3245, 7675, 90, 17128, 734, 774, 58, 17128, 63, 90, 17128, 734, 8009, 3184, 5103, 18, 2469, 422, 374, 13, 288, 203, 5411, 389, 588, 3245, 7675, 90, 17128, 5103, 18, 6206, 12, 90, 17128, 734, 1769, 203, 3639, 289, 203, 203, 3639, 776, 17128, 2502, 331, 17128, 273, 389, 588, 3245, 7675, 90, 17128, 734, 774, 58, 17128, 63, 90, 17128, 734, 15533, 203, 3639, 1731, 1578, 13737, 273, 389, 588, 2157, 734, 12, 90, 17128, 734, 16, 845, 1253, 1769, 203, 3639, 776, 17128, 2157, 2502, 1339, 273, 331, 17128, 18, 17255, 774, 2157, 63, 17255, 15533, 203, 203, 3639, 1339, 18, 1916, 1253, 273, 845, 1253, 31, 203, 3639, 1339, 18, 1937, 4921, 273, 1203, 18, 5508, 31, 203, 3639, 1339, 18, 2327, 273, 2685, 18, 9217, 31, 203, 3639, 331, 17128, 18, 3184, 5103, 18, 6206, 12, 17255, 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 ]
./partial_match/1/0x9A93a421b74F1c5755b83dD2C211614dC419C44b/sources/src/libraries/JoeLibrary.sol
given an output amount of an asset and pair reserves, returns a required input amount of the other asset
function getAmountIn(uint256 amountOut, uint256 reserveIn, uint256 reserveOut) internal pure returns (uint256 amountIn) { if (amountOut == 0) revert JoeLibrary__InsufficientAmount(); if (reserveIn == 0 || reserveOut == 0) revert JoeLibrary__InsufficientLiquidity(); uint256 numerator = reserveIn * amountOut * 1000; uint256 denominator = (reserveOut - amountOut) * 997; amountIn = numerator / denominator + 1; }
9,304,686
[ 1, 10822, 392, 876, 3844, 434, 392, 3310, 471, 3082, 400, 264, 3324, 16, 1135, 279, 1931, 810, 3844, 434, 326, 1308, 3310, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 24418, 382, 12, 11890, 5034, 3844, 1182, 16, 2254, 5034, 20501, 382, 16, 2254, 5034, 20501, 1182, 13, 203, 3639, 2713, 203, 3639, 16618, 203, 3639, 1135, 261, 11890, 5034, 3844, 382, 13, 203, 565, 288, 203, 3639, 309, 261, 8949, 1182, 422, 374, 13, 15226, 804, 15548, 9313, 972, 5048, 11339, 6275, 5621, 203, 3639, 309, 261, 455, 6527, 382, 422, 374, 747, 20501, 1182, 422, 374, 13, 15226, 804, 15548, 9313, 972, 5048, 11339, 48, 18988, 24237, 5621, 203, 3639, 2254, 5034, 16730, 273, 20501, 382, 380, 3844, 1182, 380, 4336, 31, 203, 3639, 2254, 5034, 15030, 273, 261, 455, 6527, 1182, 300, 3844, 1182, 13, 380, 2468, 10580, 31, 203, 3639, 3844, 382, 273, 16730, 342, 15030, 397, 404, 31, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/5/0xDd9395cAb14e4C788ca0BFdBabB53f744Dac6ebA/sources/contracts/ERC1155CollectionBase.sol
* @dev Return whether to use our own mint count vs balanceOf. Tokens minted via `premint` and `claim`, for example, don't affect mint count./
function _shouldUseMintCount() internal view returns (bool) { return !transferLocked && (purchaseLimit > 0 || presalePurchaseLimit > 0); }
7,083,494
[ 1, 990, 2856, 358, 999, 3134, 4953, 312, 474, 1056, 6195, 11013, 951, 18, 13899, 312, 474, 329, 3970, 1375, 1484, 81, 474, 68, 471, 1375, 14784, 9191, 364, 3454, 16, 2727, 1404, 13418, 312, 474, 1056, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 13139, 3727, 49, 474, 1380, 1435, 2713, 1476, 1135, 261, 6430, 13, 288, 203, 3639, 327, 401, 13866, 8966, 597, 261, 12688, 12104, 3039, 405, 374, 747, 4075, 5349, 23164, 3039, 405, 374, 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 ]
pragma solidity ^0.5.0; /** * @title Tellor Transfer * @dev Contais the methods related to transfers and ERC20. Tellor.sol and TellorGetters.sol * reference this library for function's logic. */ library TellorTransfer { using SafeMath for uint256; event Approval(address indexed _owner, address indexed _spender, uint256 _value); //ERC20 Approval event event Transfer(address indexed _from, address indexed _to, uint256 _value); //ERC20 Transfer Event /*Functions*/ /** * @dev Allows for a transfer of tokens to _to * @param _to The address to send tokens to * @param _amount The amount of tokens to send * @return true if transfer is successful */ function transfer(TellorStorage.TellorStorageStruct storage self, address _to, uint256 _amount) public returns (bool success) { doTransfer(self, msg.sender, _to, _amount); return true; } /** * @notice Send _amount tokens to _to from _from on the condition it * is approved by _from * @param _from The address holding the tokens being transferred * @param _to The address of the recipient * @param _amount The amount of tokens to be transferred * @return True if the transfer was successful */ function transferFrom(TellorStorage.TellorStorageStruct storage self, address _from, address _to, uint256 _amount) public returns (bool success) { require(self.allowed[_from][msg.sender] >= _amount, "Allowance is wrong"); self.allowed[_from][msg.sender] -= _amount; doTransfer(self, _from, _to, _amount); return true; } /** * @dev This function approves a _spender an _amount of tokens to use * @param _spender address * @param _amount amount the spender is being approved for * @return true if spender appproved successfully */ function approve(TellorStorage.TellorStorageStruct storage self, address _spender, uint256 _amount) public returns (bool) { require(_spender != address(0), "Spender is 0-address"); self.allowed[msg.sender][_spender] = _amount; emit Approval(msg.sender, _spender, _amount); return true; } /** * @param _user address of party with the balance * @param _spender address of spender of parties said balance * @return Returns the remaining allowance of tokens granted to the _spender from the _user */ function allowance(TellorStorage.TellorStorageStruct storage self, address _user, address _spender) public view returns (uint256) { return self.allowed[_user][_spender]; } /** * @dev Completes POWO transfers by updating the balances on the current block number * @param _from address to transfer from * @param _to addres to transfer to * @param _amount to transfer */ function doTransfer(TellorStorage.TellorStorageStruct storage self, address _from, address _to, uint256 _amount) public { require(_amount > 0, "Tried to send non-positive amount"); require(_to != address(0), "Receiver is 0 address"); //allowedToTrade checks the stakeAmount is removed from balance if the _user is staked require(allowedToTrade(self, _from, _amount), "Stake amount was not removed from balance"); uint256 previousBalance = balanceOfAt(self, _from, block.number); updateBalanceAtNow(self.balances[_from], previousBalance - _amount); previousBalance = balanceOfAt(self, _to, block.number); require(previousBalance + _amount >= previousBalance, "Overflow happened"); // Check for overflow updateBalanceAtNow(self.balances[_to], previousBalance + _amount); emit Transfer(_from, _to, _amount); } /** * @dev Gets balance of owner specified * @param _user is the owner address used to look up the balance * @return Returns the balance associated with the passed in _user */ function balanceOf(TellorStorage.TellorStorageStruct storage self, address _user) public view returns (uint256) { return balanceOfAt(self, _user, block.number); } /** * @dev Queries the balance of _user at a specific _blockNumber * @param _user The address from which the balance will be retrieved * @param _blockNumber The block number when the balance is queried * @return The balance at _blockNumber specified */ function balanceOfAt(TellorStorage.TellorStorageStruct storage self, address _user, uint256 _blockNumber) public view returns (uint256) { if ((self.balances[_user].length == 0) || (self.balances[_user][0].fromBlock > _blockNumber)) { return 0; } else { return getBalanceAt(self.balances[_user], _blockNumber); } } /** * @dev Getter for balance for owner on the specified _block number * @param checkpoints gets the mapping for the balances[owner] * @param _block is the block number to search the balance on * @return the balance at the checkpoint */ function getBalanceAt(TellorStorage.Checkpoint[] storage checkpoints, uint256 _block) public view returns (uint256) { if (checkpoints.length == 0) return 0; if (_block >= checkpoints[checkpoints.length - 1].fromBlock) return checkpoints[checkpoints.length - 1].value; if (_block < checkpoints[0].fromBlock) return 0; // Binary search of the value in the array uint256 min = 0; uint256 max = checkpoints.length - 1; while (max > min) { uint256 mid = (max + min + 1) / 2; if (checkpoints[mid].fromBlock <= _block) { min = mid; } else { max = mid - 1; } } return checkpoints[min].value; } /** * @dev This function returns whether or not a given user is allowed to trade a given amount * and removing the staked amount from their balance if they are staked * @param _user address of user * @param _amount to check if the user can spend * @return true if they are allowed to spend the amount being checked */ function allowedToTrade(TellorStorage.TellorStorageStruct storage self, address _user, uint256 _amount) public view returns (bool) { if (self.stakerDetails[_user].currentStatus > 0) { //Removes the stakeAmount from balance if the _user is staked if (balanceOf(self, _user).sub(self.uintVars[keccak256("stakeAmount")]).sub(_amount) >= 0) { return true; } } else if (balanceOf(self, _user).sub(_amount) >= 0) { return true; } return false; } /** * @dev Updates balance for from and to on the current block number via doTransfer * @param checkpoints gets the mapping for the balances[owner] * @param _value is the new balance */ function updateBalanceAtNow(TellorStorage.Checkpoint[] storage checkpoints, uint256 _value) public { if ((checkpoints.length == 0) || (checkpoints[checkpoints.length - 1].fromBlock < block.number)) { TellorStorage.Checkpoint storage newCheckPoint = checkpoints[checkpoints.length++]; newCheckPoint.fromBlock = uint128(block.number); newCheckPoint.value = uint128(_value); } else { TellorStorage.Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length - 1]; oldCheckPoint.value = uint128(_value); } } } //import "./SafeMath.sol"; /** * @title Tellor Dispute * @dev Contains the methods related to disputes. Tellor.sol references this library for function's logic. */ library TellorDispute { using SafeMath for uint256; using SafeMath for int256; //emitted when a new dispute is initialized event NewDispute(uint256 indexed _disputeId, uint256 indexed _requestId, uint256 _timestamp, address _miner); //emitted when a new vote happens event Voted(uint256 indexed _disputeID, bool _position, address indexed _voter); //emitted upon dispute tally event DisputeVoteTallied(uint256 indexed _disputeID, int256 _result, address indexed _reportedMiner, address _reportingParty, bool _active); event NewTellorAddress(address _newTellor); //emmited when a proposed fork is voted true /*Functions*/ /** * @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(TellorStorage.TellorStorageStruct storage self, uint256 _requestId, uint256 _timestamp, uint256 _minerIndex) public { TellorStorage.Request storage _request = self.requestDetails[_requestId]; //require that no more than a day( (24 hours * 60 minutes)/10minutes=144 blocks) has gone by since the value was "mined" require(now - _timestamp <= 1 days, "The value was mined more than a day ago"); require(_request.minedBlockNum[_timestamp] > 0, "Mined block is 0"); require(_minerIndex < 5, "Miner index is wrong"); //_miner is the miner being disputed. For every mined value 5 miners are saved in an array and the _minerIndex //provided by the party initiating the dispute address _miner = _request.minersByValue[_timestamp][_minerIndex]; bytes32 _hash = keccak256(abi.encodePacked(_miner, _requestId, _timestamp)); //Ensures that a dispute is not already open for the that miner, requestId and timestamp require(self.disputeIdByDisputeHash[_hash] == 0, "Dispute is already open"); TellorTransfer.doTransfer(self, msg.sender, address(this), self.uintVars[keccak256("disputeFee")]); //Increase the dispute count by 1 self.uintVars[keccak256("disputeCount")] = self.uintVars[keccak256("disputeCount")] + 1; //Sets the new disputeCount as the disputeId uint256 disputeId = self.uintVars[keccak256("disputeCount")]; //maps the dispute hash to the disputeId self.disputeIdByDisputeHash[_hash] = disputeId; //maps the dispute to the Dispute struct self.disputesById[disputeId] = TellorStorage.Dispute({ hash: _hash, isPropFork: false, reportedMiner: _miner, reportingParty: msg.sender, proposedForkAddress: address(0), executed: false, disputeVotePassed: false, tally: 0 }); //Saves all the dispute variables for the disputeId self.disputesById[disputeId].disputeUintVars[keccak256("requestId")] = _requestId; self.disputesById[disputeId].disputeUintVars[keccak256("timestamp")] = _timestamp; self.disputesById[disputeId].disputeUintVars[keccak256("value")] = _request.valuesByTimestamp[_timestamp][_minerIndex]; self.disputesById[disputeId].disputeUintVars[keccak256("minExecutionDate")] = now + 7 days; self.disputesById[disputeId].disputeUintVars[keccak256("blockNumber")] = block.number; self.disputesById[disputeId].disputeUintVars[keccak256("minerSlot")] = _minerIndex; self.disputesById[disputeId].disputeUintVars[keccak256("fee")] = self.uintVars[keccak256("disputeFee")]; //Values are sorted as they come in and the official value is the median of the first five //So the "official value" miner is always minerIndex==2. If the official value is being //disputed, it sets its status to inDispute(currentStatus = 3) so that users are made aware it is under dispute if (_minerIndex == 2) { self.requestDetails[_requestId].inDispute[_timestamp] = true; } self.stakerDetails[_miner].currentStatus = 3; emit NewDispute(disputeId, _requestId, _timestamp, _miner); } /** * @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(TellorStorage.TellorStorageStruct storage self, uint256 _disputeId, bool _supportsDispute) public { TellorStorage.Dispute storage disp = self.disputesById[_disputeId]; //Get the voteWeight or the balance of the user at the time/blockNumber the disupte began uint256 voteWeight = TellorTransfer.balanceOfAt(self, msg.sender, disp.disputeUintVars[keccak256("blockNumber")]); //Require that the msg.sender has not voted require(disp.voted[msg.sender] != true, "Sender has already voted"); //Requre that the user had a balance >0 at time/blockNumber the disupte began require(voteWeight > 0, "User balance is 0"); //ensures miners that are under dispute cannot vote require(self.stakerDetails[msg.sender].currentStatus != 3, "Miner is under dispute"); //Update user voting status to true disp.voted[msg.sender] = true; //Update the number of votes for the dispute disp.disputeUintVars[keccak256("numberOfVotes")] += 1; //Update the quorum by adding the voteWeight disp.disputeUintVars[keccak256("quorum")] += voteWeight; //If the user supports the dispute increase the tally for the dispute by the voteWeight //otherwise decrease it if (_supportsDispute) { disp.tally = disp.tally.add(int256(voteWeight)); } else { disp.tally = disp.tally.sub(int256(voteWeight)); } //Let the network know the user has voted on the dispute and their casted vote emit Voted(_disputeId, _supportsDispute, msg.sender); } /** * @dev tallies the votes. * @param _disputeId is the dispute id */ function tallyVotes(TellorStorage.TellorStorageStruct storage self, uint256 _disputeId) public { TellorStorage.Dispute storage disp = self.disputesById[_disputeId]; TellorStorage.Request storage _request = self.requestDetails[disp.disputeUintVars[keccak256("requestId")]]; //Ensure this has not already been executed/tallied require(disp.executed == false, "Dispute has been already executed"); //Ensure the time for voting has elapsed require(now > disp.disputeUintVars[keccak256("minExecutionDate")], "Time for voting haven't elapsed"); //If the vote is not a proposed fork if (disp.isPropFork == false) { TellorStorage.StakeInfo storage stakes = self.stakerDetails[disp.reportedMiner]; //If the vote for disputing a value is succesful(disp.tally >0) then unstake the reported // miner and transfer the stakeAmount and dispute fee to the reporting party if (disp.tally > 0) { //if reported miner stake has not been slashed yet, slash them and return the fee to reporting party if (stakes.currentStatus == 3) { //Changing the currentStatus and startDate unstakes the reported miner and allows for the //transfer of the stakeAmount stakes.currentStatus = 0; stakes.startDate = now - (now % 86400); //Decreases the stakerCount since the miner's stake is being slashed self.uintVars[keccak256("stakerCount")]--; updateDisputeFee(self); //Transfers the StakeAmount from the reporded miner to the reporting party TellorTransfer.doTransfer(self, disp.reportedMiner, disp.reportingParty, self.uintVars[keccak256("stakeAmount")]); //Returns the dispute fee to the reportingParty TellorTransfer.doTransfer(self, address(this), disp.reportingParty, disp.disputeUintVars[keccak256("fee")]); //if reported miner stake was already slashed, return the fee to other reporting paties } else{ TellorTransfer.doTransfer(self, address(this), disp.reportingParty, disp.disputeUintVars[keccak256("fee")]); } //Set the dispute state to passed/true disp.disputeVotePassed = true; //If the dispute was succeful(miner found guilty) then update the timestamp value to zero //so that users don't use this datapoint if (_request.inDispute[disp.disputeUintVars[keccak256("timestamp")]] == true) { _request.finalValues[disp.disputeUintVars[keccak256("timestamp")]] = 0; } //If the vote for disputing a value is unsuccesful then update the miner status from being on //dispute(currentStatus=3) to staked(currentStatus =1) and tranfer the dispute fee to the miner } else { //Update the miner's current status to staked(currentStatus = 1) stakes.currentStatus = 1; //tranfer the dispute fee to the miner TellorTransfer.doTransfer(self, address(this), disp.reportedMiner, disp.disputeUintVars[keccak256("fee")]); if (_request.inDispute[disp.disputeUintVars[keccak256("timestamp")]] == true) { _request.inDispute[disp.disputeUintVars[keccak256("timestamp")]] = false; } } //If the vote is for a proposed fork require a 20% quorum before executing the update to the new tellor contract address } else { if (disp.tally > 0) { require( disp.disputeUintVars[keccak256("quorum")] > ((self.uintVars[keccak256("total_supply")] * 20) / 100), "Quorum is not reached" ); self.addressVars[keccak256("tellorContract")] = disp.proposedForkAddress; disp.disputeVotePassed = true; emit NewTellorAddress(disp.proposedForkAddress); } } //update the dispute status to executed disp.executed = true; emit DisputeVoteTallied(_disputeId, disp.tally, disp.reportedMiner, disp.reportingParty, disp.disputeVotePassed); } /** * @dev Allows for a fork to be proposed * @param _propNewTellorAddress address for new proposed Tellor */ function proposeFork(TellorStorage.TellorStorageStruct storage self, address _propNewTellorAddress) public { bytes32 _hash = keccak256(abi.encodePacked(_propNewTellorAddress)); require(self.disputeIdByDisputeHash[_hash] == 0, ""); TellorTransfer.doTransfer(self, msg.sender, address(this), self.uintVars[keccak256("disputeFee")]); //This is the fork fee self.uintVars[keccak256("disputeCount")]++; uint256 disputeId = self.uintVars[keccak256("disputeCount")]; self.disputeIdByDisputeHash[_hash] = disputeId; self.disputesById[disputeId] = TellorStorage.Dispute({ hash: _hash, isPropFork: true, reportedMiner: msg.sender, reportingParty: msg.sender, proposedForkAddress: _propNewTellorAddress, executed: false, disputeVotePassed: false, tally: 0 }); self.disputesById[disputeId].disputeUintVars[keccak256("blockNumber")] = block.number; self.disputesById[disputeId].disputeUintVars[keccak256("fee")] = self.uintVars[keccak256("disputeFee")]; self.disputesById[disputeId].disputeUintVars[keccak256("minExecutionDate")] = now + 7 days; } /** * @dev this function allows the dispute fee to fluctuate based on the number of miners on the system. * The floor for the fee is 15e18. */ function updateDisputeFee(TellorStorage.TellorStorageStruct storage self) public { //if the number of staked miners divided by the target count of staked miners is less than 1 if ((self.uintVars[keccak256("stakerCount")] * 1000) / self.uintVars[keccak256("targetMiners")] < 1000) { //Set the dispute fee at stakeAmt * (1- stakerCount/targetMiners) //or at the its minimum of 15e18 self.uintVars[keccak256("disputeFee")] = SafeMath.max( 15e18, self.uintVars[keccak256("stakeAmount")].mul( 1000 - (self.uintVars[keccak256("stakerCount")] * 1000) / self.uintVars[keccak256("targetMiners")] ) / 1000 ); } else { //otherwise set the dispute fee at 15e18 (the floor/minimum fee allowed) self.uintVars[keccak256("disputeFee")] = 15e18; } } } /** * itle Tellor Dispute * @dev Contais the methods related to miners staking and unstaking. Tellor.sol * references this library for function's logic. */ library TellorStake { event NewStake(address indexed _sender); //Emits upon new staker event StakeWithdrawn(address indexed _sender); //Emits when a staker is now no longer staked event StakeWithdrawRequested(address indexed _sender); //Emits when a staker begins the 7 day withdraw period /*Functions*/ /** * @dev This function stakes the five initial miners, sets the supply and all the constant variables. * This function is called by the constructor function on TellorMaster.sol */ function init(TellorStorage.TellorStorageStruct storage self) public { require(self.uintVars[keccak256("decimals")] == 0, "Too many decimals"); //Give this contract 6000 Tellor Tributes so that it can stake the initial 6 miners TellorTransfer.updateBalanceAtNow(self.balances[address(this)], 2**256 - 1 - 6000e18); // //the initial 5 miner addresses are specfied below // //changed payable[5] to 6 address payable[6] memory _initalMiners = [ address(0xE037EC8EC9ec423826750853899394dE7F024fee), address(0xcdd8FA31AF8475574B8909F135d510579a8087d3), address(0xb9dD5AfD86547Df817DA2d0Fb89334A6F8eDd891), address(0x230570cD052f40E14C14a81038c6f3aa685d712B), address(0x3233afA02644CCd048587F8ba6e99b3C00A34DcC), address(0xe010aC6e0248790e08F42d5F697160DEDf97E024) ]; //Stake each of the 5 miners specified above for (uint256 i = 0; i < 6; i++) { //6th miner to allow for dispute //Miner balance is set at 1000e18 at the block that this function is ran TellorTransfer.updateBalanceAtNow(self.balances[_initalMiners[i]], 1000e18); newStake(self, _initalMiners[i]); } //update the total suppply self.uintVars[keccak256("total_supply")] += 6000e18; //6th miner to allow for dispute //set Constants self.uintVars[keccak256("decimals")] = 18; self.uintVars[keccak256("targetMiners")] = 200; self.uintVars[keccak256("stakeAmount")] = 1000e18; self.uintVars[keccak256("disputeFee")] = 970e18; self.uintVars[keccak256("timeTarget")] = 600; self.uintVars[keccak256("timeOfLastNewValue")] = now - (now % self.uintVars[keccak256("timeTarget")]); self.uintVars[keccak256("difficulty")] = 1; } /** * @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 deposit */ function requestStakingWithdraw(TellorStorage.TellorStorageStruct storage self) public { TellorStorage.StakeInfo storage stakes = self.stakerDetails[msg.sender]; //Require that the miner is staked require(stakes.currentStatus == 1, "Miner is not staked"); //Change the miner staked to locked to be withdrawStake stakes.currentStatus = 2; //Change the startDate to now since the lock up period begins now //and the miner can only withdraw 7 days later from now(check the withdraw function) stakes.startDate = now - (now % 86400); //Reduce the staker count self.uintVars[keccak256("stakerCount")] -= 1; TellorDispute.updateDisputeFee(self); emit StakeWithdrawRequested(msg.sender); } /** * @dev This function allows users to withdraw their stake after a 7 day waiting period from request */ function withdrawStake(TellorStorage.TellorStorageStruct storage self) public { TellorStorage.StakeInfo storage stakes = self.stakerDetails[msg.sender]; //Require the staker has locked for withdraw(currentStatus ==2) and that 7 days have //passed by since they locked for withdraw require(now - (now % 86400) - stakes.startDate >= 7 days, "7 days didn't pass"); require(stakes.currentStatus == 2, "Miner was not locked for withdrawal"); stakes.currentStatus = 0; emit StakeWithdrawn(msg.sender); } /** * @dev This function allows miners to deposit their stake. */ function depositStake(TellorStorage.TellorStorageStruct storage self) public { newStake(self, msg.sender); //self adjusting disputeFee TellorDispute.updateDisputeFee(self); } /** * @dev This function is used by the init function to succesfully stake the initial 5 miners. * The function updates their status/state and status start date so they are locked it so they can't withdraw * and updates the number of stakers in the system. */ function newStake(TellorStorage.TellorStorageStruct storage self, address staker) internal { require(TellorTransfer.balanceOf(self, staker) >= self.uintVars[keccak256("stakeAmount")], "Balance is lower than stake amount"); //Ensure they can only stake if they are not currrently staked or if their stake time frame has ended //and they are currently locked for witdhraw require(self.stakerDetails[staker].currentStatus == 0 || self.stakerDetails[staker].currentStatus == 2, "Miner is in the wrong state"); self.uintVars[keccak256("stakerCount")] += 1; self.stakerDetails[staker] = TellorStorage.StakeInfo({ currentStatus: 1, //this resets their stake start date to today startDate: now - (now % 86400) }); emit NewStake(staker); } } //Slightly modified SafeMath library - includes a min and max function, removes useless div function library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } function add(int256 a, int256 b) internal pure returns (int256 c) { if (b > 0) { c = a + b; assert(c >= a); } else { c = a + b; assert(c <= a); } } function max(uint256 a, uint256 b) internal pure returns (uint256) { return a > b ? a : b; } function max(int256 a, int256 b) internal pure returns (uint256) { return a > b ? uint256(a) : uint256(b); } function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function sub(int256 a, int256 b) internal pure returns (int256 c) { if (b > 0) { c = a - b; assert(c <= a); } else { c = a - b; assert(c >= a); } } } /** * @title Tellor Oracle Storage Library * @dev Contains all the variables/structs used by Tellor */ library TellorStorage { //Internal struct for use in proof-of-work submission struct Details { uint256 value; address miner; } struct Dispute { bytes32 hash; //unique hash of dispute: keccak256(_miner,_requestId,_timestamp) int256 tally; //current tally of votes for - against measure bool executed; //is the dispute settled bool disputeVotePassed; //did the vote pass? bool isPropFork; //true for fork proposal NEW address reportedMiner; //miner who alledgedly submitted the 'bad value' will get disputeFee if dispute vote fails address reportingParty; //miner reporting the 'bad value'-pay disputeFee will get reportedMiner's stake if dispute vote passes address proposedForkAddress; //new fork address (if fork proposal) mapping(bytes32 => uint256) disputeUintVars; //Each of the variables below is saved in the mapping disputeUintVars for each disputeID //e.g. TellorStorageStruct.DisputeById[disputeID].disputeUintVars[keccak256("requestId")] //These are the variables saved in this mapping: // uint keccak256("requestId");//apiID of disputed value // uint keccak256("timestamp");//timestamp of distputed value // uint keccak256("value"); //the value being disputed // uint keccak256("minExecutionDate");//7 days from when dispute initialized // uint keccak256("numberOfVotes");//the number of parties who have voted on the measure // uint keccak256("blockNumber");// the blocknumber for which votes will be calculated from // uint keccak256("minerSlot"); //index in dispute array // uint keccak256("quorum"); //quorum for dispute vote NEW // uint keccak256("fee"); //fee paid corresponding to dispute mapping(address => bool) voted; //mapping of address to whether or not they voted } struct StakeInfo { uint256 currentStatus; //0-not Staked, 1=Staked, 2=LockedForWithdraw 3= OnDispute uint256 startDate; //stake start date } //Internal struct to allow balances to be queried by blocknumber for voting purposes struct Checkpoint { uint128 fromBlock; // fromBlock is the block number that the value was generated from uint128 value; // value is the amount of tokens at a specific block number } struct Request { string queryString; //id to string api string dataSymbol; //short name for api request bytes32 queryHash; //hash of api string and granularity e.g. keccak256(abi.encodePacked(_sapi,_granularity)) uint256[] requestTimestamps; //array of all newValueTimestamps requested mapping(bytes32 => uint256) apiUintVars; //Each of the variables below is saved in the mapping apiUintVars for each api request //e.g. requestDetails[_requestId].apiUintVars[keccak256("totalTip")] //These are the variables saved in this mapping: // uint keccak256("granularity"); //multiplier for miners // uint keccak256("requestQPosition"); //index in requestQ // uint keccak256("totalTip");//bonus portion of payout mapping(uint256 => uint256) minedBlockNum; //[apiId][minedTimestamp]=>block.number //This the time series of finalValues stored by the contract where uint UNIX timestamp is mapped to value mapping(uint256 => uint256) finalValues; mapping(uint256 => bool) inDispute; //checks if API id is in dispute or finalized. mapping(uint256 => address[5]) minersByValue; mapping(uint256 => uint256[5]) valuesByTimestamp; } struct TellorStorageStruct { bytes32 currentChallenge; //current challenge to be solved uint256[51] requestQ; //uint50 array of the top50 requests by payment amount uint256[] newValueTimestamps; //array of all timestamps requested Details[5] currentMiners; //This struct is for organizing the five mined values to find the median mapping(bytes32 => address) addressVars; //Address fields in the Tellor contract are saved the addressVars mapping //e.g. addressVars[keccak256("tellorContract")] = address //These are the variables saved in this mapping: // address keccak256("tellorContract");//Tellor address // address keccak256("_owner");//Tellor Owner address // address keccak256("_deity");//Tellor Owner that can do things at will mapping(bytes32 => uint256) uintVars; //uint fields in the Tellor contract are saved the uintVars mapping //e.g. uintVars[keccak256("decimals")] = uint //These are the variables saved in this mapping: // keccak256("decimals"); //18 decimal standard ERC20 // keccak256("disputeFee");//cost to dispute a mined value // keccak256("disputeCount");//totalHistoricalDisputes // keccak256("total_supply"); //total_supply of the token in circulation // keccak256("stakeAmount");//stakeAmount for miners (we can cut gas if we just hardcode it in...or should it be variable?) // keccak256("stakerCount"); //number of parties currently staked // keccak256("timeOfLastNewValue"); // time of last challenge solved // keccak256("difficulty"); // Difficulty of current block // keccak256("currentTotalTips"); //value of highest api/timestamp PayoutPool // keccak256("currentRequestId"); //API being mined--updates with the ApiOnQ Id // keccak256("requestCount"); // total number of requests through the system // keccak256("slotProgress");//Number of miners who have mined this value so far // keccak256("miningReward");//Mining Reward in PoWo tokens given to all miners per value // keccak256("timeTarget"); //The time between blocks (mined Oracle values) //This is a boolean that tells you if a given challenge has been completed by a given miner mapping(bytes32 => mapping(address => bool)) minersByChallenge; mapping(uint256 => uint256) requestIdByTimestamp; //minedTimestamp to apiId mapping(uint256 => uint256) requestIdByRequestQIndex; //link from payoutPoolIndex (position in payout pool array) to apiId mapping(uint256 => Dispute) disputesById; //disputeId=> Dispute details mapping(address => Checkpoint[]) balances; //balances of a party given blocks mapping(address => mapping(address => uint256)) allowed; //allowance for a given party and approver mapping(address => StakeInfo) stakerDetails; //mapping from a persons address to their staking info mapping(uint256 => Request) requestDetails; //mapping of apiID to details mapping(bytes32 => uint256) requestIdByQueryHash; // api bytes32 gets an id = to count of requests array mapping(bytes32 => uint256) disputeIdByDisputeHash; //maps a hash to an ID for each dispute } } //Functions for retrieving min and Max in 51 length array (requestQ) //Taken partly from: https://github.com/modular-network/ethereum-libraries-array-utils/blob/master/contracts/Array256Lib.sol library Utilities { /** * @dev Returns the minimum value in an array. */ function getMax(uint256[51] memory data) internal pure returns (uint256 max, uint256 maxIndex) { max = data[1]; maxIndex; for (uint256 i = 1; i < data.length; i++) { if (data[i] > max) { max = data[i]; maxIndex = i; } } } /** * @dev Returns the minimum value in an array. */ function getMin(uint256[51] memory data) internal pure returns (uint256 min, uint256 minIndex) { minIndex = data.length - 1; min = data[minIndex]; for (uint256 i = data.length - 1; i > 0; i--) { if (data[i] < min) { min = data[i]; minIndex = i; } } } } /** * @title Tellor Getters Library * @dev This is the getter library for all variables in the Tellor Tributes system. TellorGetters references this * libary for the getters logic */ library TellorGettersLibrary { using SafeMath for uint256; event NewTellorAddress(address _newTellor); //emmited when a proposed fork is voted true /*Functions*/ //The next two functions are onlyOwner functions. For Tellor to be truly decentralized, we will need to transfer the Deity to the 0 address. //Only needs to be in library /** * @dev This function allows us to set a new Deity (or remove it) * @param _newDeity address of the new Deity of the tellor system */ function changeDeity(TellorStorage.TellorStorageStruct storage self, address _newDeity) internal { require(self.addressVars[keccak256("_deity")] == msg.sender, "Sender is not deity"); self.addressVars[keccak256("_deity")] = _newDeity; } //Only needs to be in library /** * @dev This function allows the deity to upgrade the Tellor System * @param _tellorContract address of new updated TellorCore contract */ function changeTellorContract(TellorStorage.TellorStorageStruct storage self, address _tellorContract) internal { require(self.addressVars[keccak256("_deity")] == msg.sender, "Sender is not deity"); self.addressVars[keccak256("tellorContract")] = _tellorContract; emit NewTellorAddress(_tellorContract); } /*Tellor Getters*/ /** * @dev This function tells you if a given challenge has been completed by a given miner * @param _challenge the challenge to search for * @param _miner address that you want to know if they solved the challenge * @return true if the _miner address provided solved the */ function didMine(TellorStorage.TellorStorageStruct storage self, bytes32 _challenge, address _miner) internal view returns (bool) { return self.minersByChallenge[_challenge][_miner]; } /** * @dev Checks if an address voted in a dispute * @param _disputeId to look up * @param _address of voting party to look up * @return bool of whether or not party voted */ function didVote(TellorStorage.TellorStorageStruct storage self, uint256 _disputeId, address _address) internal view returns (bool) { return self.disputesById[_disputeId].voted[_address]; } /** * @dev allows Tellor to read data from the addressVars mapping * @param _data is the keccak256("variable_name") of the variable that is being accessed. * These are examples of how the variables are saved within other functions: * addressVars[keccak256("_owner")] * addressVars[keccak256("tellorContract")] */ function getAddressVars(TellorStorage.TellorStorageStruct storage self, bytes32 _data) internal view returns (address) { return self.addressVars[_data]; } /** * @dev Gets all dispute variables * @param _disputeId to look up * @return bytes32 hash of dispute * @return bool executed where true if it has been voted on * @return bool disputeVotePassed * @return bool isPropFork true if the dispute is a proposed fork * @return address of reportedMiner * @return address of reportingParty * @return address of proposedForkAddress * @return uint of requestId * @return uint of timestamp * @return uint of value * @return uint of minExecutionDate * @return uint of numberOfVotes * @return uint of blocknumber * @return uint of minerSlot * @return uint of quorum * @return uint of fee * @return int count of the current tally */ function getAllDisputeVars(TellorStorage.TellorStorageStruct storage self, uint256 _disputeId) internal view returns (bytes32, bool, bool, bool, address, address, address, uint256[9] memory, int256) { TellorStorage.Dispute storage disp = self.disputesById[_disputeId]; return ( disp.hash, disp.executed, disp.disputeVotePassed, disp.isPropFork, disp.reportedMiner, disp.reportingParty, disp.proposedForkAddress, [ disp.disputeUintVars[keccak256("requestId")], disp.disputeUintVars[keccak256("timestamp")], disp.disputeUintVars[keccak256("value")], disp.disputeUintVars[keccak256("minExecutionDate")], disp.disputeUintVars[keccak256("numberOfVotes")], disp.disputeUintVars[keccak256("blockNumber")], disp.disputeUintVars[keccak256("minerSlot")], disp.disputeUintVars[keccak256("quorum")], disp.disputeUintVars[keccak256("fee")] ], disp.tally ); } /** * @dev Getter function for variables for the requestId being currently mined(currentRequestId) * @return current challenge, curretnRequestId, level of difficulty, api/query string, and granularity(number of decimals requested), total tip for the request */ function getCurrentVariables(TellorStorage.TellorStorageStruct storage self) internal view returns (bytes32, uint256, uint256, string memory, uint256, uint256) { return ( self.currentChallenge, self.uintVars[keccak256("currentRequestId")], self.uintVars[keccak256("difficulty")], self.requestDetails[self.uintVars[keccak256("currentRequestId")]].queryString, self.requestDetails[self.uintVars[keccak256("currentRequestId")]].apiUintVars[keccak256("granularity")], self.requestDetails[self.uintVars[keccak256("currentRequestId")]].apiUintVars[keccak256("totalTip")] ); } /** * @dev Checks if a given hash of miner,requestId has been disputed * @param _hash is the sha256(abi.encodePacked(_miners[2],_requestId)); * @return uint disputeId */ function getDisputeIdByDisputeHash(TellorStorage.TellorStorageStruct storage self, bytes32 _hash) internal view returns (uint256) { return self.disputeIdByDisputeHash[_hash]; } /** * @dev Checks for uint variables in the disputeUintVars mapping based on the disuputeId * @param _disputeId is the dispute id; * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the disputeUintVars under the Dispute struct * @return uint value for the bytes32 data submitted */ function getDisputeUintVars(TellorStorage.TellorStorageStruct storage self, uint256 _disputeId, bytes32 _data) internal view returns (uint256) { return self.disputesById[_disputeId].disputeUintVars[_data]; } /** * @dev Gets the a value for the latest timestamp available * @return value for timestamp of last proof of work submited * @return true if the is a timestamp for the lastNewValue */ function getLastNewValue(TellorStorage.TellorStorageStruct storage self) internal view returns (uint256, bool) { return ( retrieveData( self, self.requestIdByTimestamp[self.uintVars[keccak256("timeOfLastNewValue")]], self.uintVars[keccak256("timeOfLastNewValue")] ), true ); } /** * @dev Gets the a value for the latest timestamp available * @param _requestId being requested * @return value for timestamp of last proof of work submited and if true if it exist or 0 and false if it doesn't */ function getLastNewValueById(TellorStorage.TellorStorageStruct storage self, uint256 _requestId) internal view returns (uint256, bool) { TellorStorage.Request storage _request = self.requestDetails[_requestId]; if (_request.requestTimestamps.length > 0) { return (retrieveData(self, _requestId, _request.requestTimestamps[_request.requestTimestamps.length - 1]), true); } else { return (0, false); } } /** * @dev Gets blocknumber for mined timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up blocknumber * @return uint of the blocknumber which the dispute was mined */ function getMinedBlockNum(TellorStorage.TellorStorageStruct storage self, uint256 _requestId, uint256 _timestamp) internal view returns (uint256) { return self.requestDetails[_requestId].minedBlockNum[_timestamp]; } /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up miners for * @return the 5 miners' addresses */ function getMinersByRequestIdAndTimestamp(TellorStorage.TellorStorageStruct storage self, uint256 _requestId, uint256 _timestamp) internal view returns (address[5] memory) { return self.requestDetails[_requestId].minersByValue[_timestamp]; } /** * @dev Get the name of the token * @return string of the token name */ function getName(TellorStorage.TellorStorageStruct storage self) internal pure returns (string memory) { return "Tellor Tributes"; } /** * @dev Counts the number of values that have been submited for the request * if called for the currentRequest being mined it can tell you how many miners have submitted a value for that * request so far * @param _requestId the requestId to look up * @return uint count of the number of values received for the requestId */ function getNewValueCountbyRequestId(TellorStorage.TellorStorageStruct storage self, uint256 _requestId) internal view returns (uint256) { return self.requestDetails[_requestId].requestTimestamps.length; } /** * @dev Getter function for the specified requestQ index * @param _index to look up in the requestQ array * @return uint of reqeuestId */ function getRequestIdByRequestQIndex(TellorStorage.TellorStorageStruct storage self, uint256 _index) internal view returns (uint256) { require(_index <= 50, "RequestQ index is above 50"); return self.requestIdByRequestQIndex[_index]; } /** * @dev Getter function for requestId based on timestamp * @param _timestamp to check requestId * @return uint of reqeuestId */ function getRequestIdByTimestamp(TellorStorage.TellorStorageStruct storage self, uint256 _timestamp) internal view returns (uint256) { return self.requestIdByTimestamp[_timestamp]; } /** * @dev Getter function for requestId based on the qeuaryHash * @param _queryHash hash(of string api and granularity) to check if a request already exists * @return uint requestId */ function getRequestIdByQueryHash(TellorStorage.TellorStorageStruct storage self, bytes32 _queryHash) internal view returns (uint256) { return self.requestIdByQueryHash[_queryHash]; } /** * @dev Getter function for the requestQ array * @return the requestQ arrray */ function getRequestQ(TellorStorage.TellorStorageStruct storage self) internal view returns (uint256[51] memory) { return self.requestQ; } /** * @dev Allowes access to the uint variables saved in the apiUintVars under the requestDetails struct * for the requestId specified * @param _requestId to look up * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the apiUintVars under the requestDetails struct * @return uint value of the apiUintVars specified in _data for the requestId specified */ function getRequestUintVars(TellorStorage.TellorStorageStruct storage self, uint256 _requestId, bytes32 _data) internal view returns (uint256) { return self.requestDetails[_requestId].apiUintVars[_data]; } /** * @dev Gets the API struct variables that are not mappings * @param _requestId to look up * @return string of api to query * @return string of symbol of api to query * @return bytes32 hash of string * @return bytes32 of the granularity(decimal places) requested * @return uint of index in requestQ array * @return uint of current payout/tip for this requestId */ function getRequestVars(TellorStorage.TellorStorageStruct storage self, uint256 _requestId) internal view returns (string memory, string memory, bytes32, uint256, uint256, uint256) { TellorStorage.Request storage _request = self.requestDetails[_requestId]; return ( _request.queryString, _request.dataSymbol, _request.queryHash, _request.apiUintVars[keccak256("granularity")], _request.apiUintVars[keccak256("requestQPosition")], _request.apiUintVars[keccak256("totalTip")] ); } /** * @dev This function allows users to retireve all information about a staker * @param _staker address of staker inquiring about * @return uint current state of staker * @return uint startDate of staking */ function getStakerInfo(TellorStorage.TellorStorageStruct storage self, address _staker) internal view returns (uint256, uint256) { return (self.stakerDetails[_staker].currentStatus, self.stakerDetails[_staker].startDate); } /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestampt to look up miners for * @return address[5] array of 5 addresses ofminers that mined the requestId */ function getSubmissionsByTimestamp(TellorStorage.TellorStorageStruct storage self, uint256 _requestId, uint256 _timestamp) internal view returns (uint256[5] memory) { return self.requestDetails[_requestId].valuesByTimestamp[_timestamp]; } /** * @dev Get the symbol of the token * @return string of the token symbol */ function getSymbol(TellorStorage.TellorStorageStruct storage self) internal pure returns (string memory) { return "TT"; } /** * @dev Gets the timestamp for the value based on their index * @param _requestID is the requestId to look up * @param _index is the value index to look up * @return uint timestamp */ function getTimestampbyRequestIDandIndex(TellorStorage.TellorStorageStruct storage self, uint256 _requestID, uint256 _index) internal view returns (uint256) { return self.requestDetails[_requestID].requestTimestamps[_index]; } /** * @dev Getter for the variables saved under the TellorStorageStruct uintVars variable * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the uintVars under the TellorStorageStruct struct * This is an example of how data is saved into the mapping within other functions: * self.uintVars[keccak256("stakerCount")] * @return uint of specified variable */ function getUintVar(TellorStorage.TellorStorageStruct storage self, bytes32 _data) internal view returns (uint256) { return self.uintVars[_data]; } /** * @dev Getter function for next requestId on queue/request with highest payout at time the function is called * @return onDeck/info on request with highest payout-- RequestId, Totaltips, and API query string */ function getVariablesOnDeck(TellorStorage.TellorStorageStruct storage self) internal view returns (uint256, uint256, string memory) { uint256 newRequestId = getTopRequestID(self); return ( newRequestId, self.requestDetails[newRequestId].apiUintVars[keccak256("totalTip")], self.requestDetails[newRequestId].queryString ); } /** * @dev Getter function for the request with highest payout. This function is used within the getVariablesOnDeck function * @return uint _requestId of request with highest payout at the time the function is called */ function getTopRequestID(TellorStorage.TellorStorageStruct storage self) internal view returns (uint256 _requestId) { uint256 _max; uint256 _index; (_max, _index) = Utilities.getMax(self.requestQ); _requestId = self.requestIdByRequestQIndex[_index]; } /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up miners for * @return bool true if requestId/timestamp is under dispute */ function isInDispute(TellorStorage.TellorStorageStruct storage self, uint256 _requestId, uint256 _timestamp) internal view returns (bool) { return self.requestDetails[_requestId].inDispute[_timestamp]; } /** * @dev Retreive value from oracle based on requestId/timestamp * @param _requestId being requested * @param _timestamp to retreive data/value from * @return uint value for requestId/timestamp submitted */ function retrieveData(TellorStorage.TellorStorageStruct storage self, uint256 _requestId, uint256 _timestamp) internal view returns (uint256) { return self.requestDetails[_requestId].finalValues[_timestamp]; } /** * @dev Getter for the total_supply of oracle tokens * @return uint total supply */ function totalSupply(TellorStorage.TellorStorageStruct storage self) internal view returns (uint256) { return self.uintVars[keccak256("total_supply")]; } } /** * @title Tellor Oracle System Library * @dev Contains the functions' logic for the Tellor contract where miners can submit the proof of work * along with the value and smart contracts can requestData and tip miners. */ library TellorLibrary { using SafeMath for uint256; event TipAdded(address indexed _sender, uint256 indexed _requestId, uint256 _tip, uint256 _totalTips); //Emits upon someone adding value to a pool; msg.sender, amount added, and timestamp incentivized to be mined event DataRequested( address indexed _sender, string _query, string _querySymbol, uint256 _granularity, uint256 indexed _requestId, uint256 _totalTips ); //emits when a new challenge is created (either on mined block or when a new request is pushed forward on waiting system) event NewChallenge( bytes32 _currentChallenge, uint256 indexed _currentRequestId, uint256 _difficulty, uint256 _multiplier, string _query, uint256 _totalTips ); //emits when a the payout of another request is higher after adding to the payoutPool or submitting a request event NewRequestOnDeck(uint256 indexed _requestId, string _query, bytes32 _onDeckQueryHash, uint256 _onDeckTotalTips); //Emits upon a successful Mine, indicates the blocktime at point of the mine and the value mined event NewValue(uint256 indexed _requestId, uint256 _time, uint256 _value, uint256 _totalTips, bytes32 _currentChallenge); //Emits upon each mine (5 total) and shows the miner, nonce, and value submitted event NonceSubmitted(address indexed _miner, string _nonce, uint256 indexed _requestId, uint256 _value, bytes32 _currentChallenge); event OwnershipTransferred(address indexed _previousOwner, address indexed _newOwner); event OwnershipProposed(address indexed _previousOwner, address indexed _newOwner); /*Functions*/ /*This is a cheat for demo purposes, will delete upon actual launch*/ /*function theLazyCoon(TellorStorage.TellorStorageStruct storage self,address _address, uint _amount) public { self.uintVars[keccak256("total_supply")] += _amount; TellorTransfer.updateBalanceAtNow(self.balances[_address],_amount); } */ /** * @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(TellorStorage.TellorStorageStruct storage self, uint256 _requestId, uint256 _tip) public { require(_requestId > 0, "RequestId is 0"); //If the tip > 0 transfer the tip to this contract if (_tip > 0) { TellorTransfer.doTransfer(self, msg.sender, address(this), _tip); } //Update the information for the request that should be mined next based on the tip submitted updateOnDeck(self, _requestId, _tip); emit TipAdded(msg.sender, _requestId, _tip, self.requestDetails[_requestId].apiUintVars[keccak256("totalTip")]); } /** * @dev Request to retreive value from oracle based on timestamp. The tip is not required to be * greater than 0 because there are no tokens in circulation for the initial(genesis) request * @param _c_sapi string API being requested be mined * @param _c_symbol is the short string symbol for the api request * @param _granularity is the number of decimals miners should include on the submitted value * @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 requestData( TellorStorage.TellorStorageStruct storage self, string memory _c_sapi, string memory _c_symbol, uint256 _granularity, uint256 _tip ) public { //Require at least one decimal place require(_granularity > 0, "Too few decimal places"); //But no more than 18 decimal places require(_granularity <= 1e18, "Too many decimal places"); //If it has been requested before then add the tip to it otherwise create the queryHash for it string memory _sapi = _c_sapi; string memory _symbol = _c_symbol; require(bytes(_sapi).length > 0, "API string length is 0"); require(bytes(_symbol).length < 64, "API string symbol is greater than 64"); bytes32 _queryHash = keccak256(abi.encodePacked(_sapi, _granularity)); //If this is the first time the API and granularity combination has been requested then create the API and granularity hash //otherwise the tip will be added to the requestId submitted if (self.requestIdByQueryHash[_queryHash] == 0) { self.uintVars[keccak256("requestCount")]++; uint256 _requestId = self.uintVars[keccak256("requestCount")]; self.requestDetails[_requestId] = TellorStorage.Request({ queryString: _sapi, dataSymbol: _symbol, queryHash: _queryHash, requestTimestamps: new uint256[](0) }); self.requestDetails[_requestId].apiUintVars[keccak256("granularity")] = _granularity; self.requestDetails[_requestId].apiUintVars[keccak256("requestQPosition")] = 0; self.requestDetails[_requestId].apiUintVars[keccak256("totalTip")] = 0; self.requestIdByQueryHash[_queryHash] = _requestId; //If the tip > 0 it tranfers the tip to this contract if (_tip > 0) { TellorTransfer.doTransfer(self, msg.sender, address(this), _tip); } updateOnDeck(self, _requestId, _tip); emit DataRequested( msg.sender, self.requestDetails[_requestId].queryString, self.requestDetails[_requestId].dataSymbol, _granularity, _requestId, _tip ); //Add tip to existing request id since this is not the first time the api and granularity have been requested } else { addTip(self, self.requestIdByQueryHash[_queryHash], _tip); } } /** * @dev This fucntion is called by submitMiningSolution and adjusts the difficulty, sorts and stores the first * 5 values received, pays the miners, the dev share and assigns a new challenge * @param _nonce or solution for the PoW for the requestId * @param _requestId for the current request being mined */ function newBlock(TellorStorage.TellorStorageStruct storage self, string memory _nonce, uint256 _requestId) internal { TellorStorage.Request storage _request = self.requestDetails[_requestId]; // If the difference between the timeTarget and how long it takes to solve the challenge this updates the challenge //difficulty up or donw by the difference between the target time and how long it took to solve the prevous challenge //otherwise it sets it to 1 int256 _change = int256(SafeMath.min(1200, (now - self.uintVars[keccak256("timeOfLastNewValue")]))); _change = (int256(self.uintVars[keccak256("difficulty")]) * (int256(self.uintVars[keccak256("timeTarget")]) - _change)) / 4000; if (_change < 2 && _change > -2) { if (_change >= 0) { _change = 1; } else { _change = -1; } } if ((int256(self.uintVars[keccak256("difficulty")]) + _change) <= 0) { self.uintVars[keccak256("difficulty")] = 1; } else { self.uintVars[keccak256("difficulty")] = uint256(int256(self.uintVars[keccak256("difficulty")]) + _change); } //Sets time of value submission rounded to 1 minute uint256 _timeOfLastNewValue = now - (now % 1 minutes); self.uintVars[keccak256("timeOfLastNewValue")] = _timeOfLastNewValue; //The sorting algorithm that sorts the values of the first five values that come in TellorStorage.Details[5] memory a = self.currentMiners; uint256 i; for (i = 1; i < 5; i++) { uint256 temp = a[i].value; address temp2 = a[i].miner; uint256 j = i; while (j > 0 && temp < a[j - 1].value) { a[j].value = a[j - 1].value; a[j].miner = a[j - 1].miner; j--; } if (j < i) { a[j].value = temp; a[j].miner = temp2; } } //Pay the miners for (i = 0; i < 5; i++) { TellorTransfer.doTransfer(self, address(this), a[i].miner, 5e18 + self.uintVars[keccak256("currentTotalTips")] / 5); } emit NewValue( _requestId, _timeOfLastNewValue, a[2].value, self.uintVars[keccak256("currentTotalTips")] - (self.uintVars[keccak256("currentTotalTips")] % 5), self.currentChallenge ); //update the total supply self.uintVars[keccak256("total_supply")] += 275e17; //pay the dev-share TellorTransfer.doTransfer(self, address(this), self.addressVars[keccak256("_owner")], 25e17); //The ten there is the devshare //Save the official(finalValue), timestamp of it, 5 miners and their submitted values for it, and its block number _request.finalValues[_timeOfLastNewValue] = a[2].value; _request.requestTimestamps.push(_timeOfLastNewValue); //these are miners by timestamp _request.minersByValue[_timeOfLastNewValue] = [a[0].miner, a[1].miner, a[2].miner, a[3].miner, a[4].miner]; _request.valuesByTimestamp[_timeOfLastNewValue] = [a[0].value, a[1].value, a[2].value, a[3].value, a[4].value]; _request.minedBlockNum[_timeOfLastNewValue] = block.number; //map the timeOfLastValue to the requestId that was just mined self.requestIdByTimestamp[_timeOfLastNewValue] = _requestId; //add timeOfLastValue to the newValueTimestamps array self.newValueTimestamps.push(_timeOfLastNewValue); //re-start the count for the slot progress to zero before the new request mining starts self.uintVars[keccak256("slotProgress")] = 0; uint256 _topId = TellorGettersLibrary.getTopRequestID(self); self.uintVars[keccak256("currentRequestId")] = _topId; //if the currentRequestId is not zero(currentRequestId exists/something is being mined) select the requestId with the hightest payout //else wait for a new tip to mine if (_topId > 0) { //Update the current request to be mined to the requestID with the highest payout self.uintVars[keccak256("currentTotalTips")] = self.requestDetails[_topId].apiUintVars[keccak256("totalTip")]; //Remove the currentRequestId/onDeckRequestId from the requestQ array containing the rest of the 50 requests self.requestQ[self.requestDetails[_topId].apiUintVars[keccak256("requestQPosition")]] = 0; //unmap the currentRequestId/onDeckRequestId from the requestIdByRequestQIndex self.requestIdByRequestQIndex[self.requestDetails[_topId].apiUintVars[keccak256("requestQPosition")]] = 0; //Remove the requestQposition for the currentRequestId/onDeckRequestId since it will be mined next self.requestDetails[_topId].apiUintVars[keccak256("requestQPosition")] = 0; //Reset the requestId TotalTip to 0 for the currentRequestId/onDeckRequestId since it will be mined next //and the tip is going to the current timestamp miners. The tip for the API needs to be reset to zero self.requestDetails[_topId].apiUintVars[keccak256("totalTip")] = 0; //gets the max tip in the in the requestQ[51] array and its index within the array?? uint256 newRequestId = TellorGettersLibrary.getTopRequestID(self); //Issue the the next challenge self.currentChallenge = keccak256(abi.encodePacked(_nonce, self.currentChallenge, blockhash(block.number - 1))); // Save hash for next proof emit NewChallenge( self.currentChallenge, _topId, self.uintVars[keccak256("difficulty")], self.requestDetails[_topId].apiUintVars[keccak256("granularity")], self.requestDetails[_topId].queryString, self.uintVars[keccak256("currentTotalTips")] ); emit NewRequestOnDeck( newRequestId, self.requestDetails[newRequestId].queryString, self.requestDetails[newRequestId].queryHash, self.requestDetails[newRequestId].apiUintVars[keccak256("totalTip")] ); } else { self.uintVars[keccak256("currentTotalTips")] = 0; self.currentChallenge = ""; } } /** * @dev Proof of work is called by the miner when they submit the solution (proof of work and value) * @param _nonce uint submitted by miner * @param _requestId the apiId being mined * @param _value of api query */ function submitMiningSolution(TellorStorage.TellorStorageStruct storage self, string memory _nonce, uint256 _requestId, uint256 _value) public { //requre miner is staked require(self.stakerDetails[msg.sender].currentStatus == 1, "Miner status is not staker"); //Check the miner is submitting the pow for the current request Id require(_requestId == self.uintVars[keccak256("currentRequestId")], "RequestId is wrong"); //Saving the challenge information as unique by using the msg.sender require( uint256( sha256(abi.encodePacked(ripemd160(abi.encodePacked(keccak256(abi.encodePacked(self.currentChallenge, msg.sender, _nonce)))))) ) % self.uintVars[keccak256("difficulty")] == 0, "Challenge information is not saved" ); //Make sure the miner does not submit a value more than once require(self.minersByChallenge[self.currentChallenge][msg.sender] == false, "Miner already submitted the value"); //Save the miner and value received self.currentMiners[self.uintVars[keccak256("slotProgress")]].value = _value; self.currentMiners[self.uintVars[keccak256("slotProgress")]].miner = msg.sender; //Add to the count how many values have been submitted, since only 5 are taken per request self.uintVars[keccak256("slotProgress")]++; //Update the miner status to true once they submit a value so they don't submit more than once self.minersByChallenge[self.currentChallenge][msg.sender] = true; emit NonceSubmitted(msg.sender, _nonce, _requestId, _value, self.currentChallenge); //If 5 values have been received, adjust the difficulty otherwise sort the values until 5 are received if (self.uintVars[keccak256("slotProgress")] == 5) { newBlock(self, _nonce, _requestId); } } /** * @dev Allows the current owner to propose transfer control of the contract to a * newOwner and the ownership is pending until the new owner calls the claimOwnership * function * @param _pendingOwner The address to transfer ownership to. */ function proposeOwnership(TellorStorage.TellorStorageStruct storage self, address payable _pendingOwner) internal { require(msg.sender == self.addressVars[keccak256("_owner")], "Sender is not owner"); emit OwnershipProposed(self.addressVars[keccak256("_owner")], _pendingOwner); self.addressVars[keccak256("pending_owner")] = _pendingOwner; } /** * @dev Allows the new owner to claim control of the contract */ function claimOwnership(TellorStorage.TellorStorageStruct storage self) internal { require(msg.sender == self.addressVars[keccak256("pending_owner")], "Sender is not pending owner"); emit OwnershipTransferred(self.addressVars[keccak256("_owner")], self.addressVars[keccak256("pending_owner")]); self.addressVars[keccak256("_owner")] = self.addressVars[keccak256("pending_owner")]; } /** * @dev This function updates APIonQ and the requestQ when requestData or addTip are ran * @param _requestId being requested * @param _tip is the tip to add */ function updateOnDeck(TellorStorage.TellorStorageStruct storage self, uint256 _requestId, uint256 _tip) internal { TellorStorage.Request storage _request = self.requestDetails[_requestId]; uint256 onDeckRequestId = TellorGettersLibrary.getTopRequestID(self); //If the tip >0 update the tip for the requestId if (_tip > 0) { _request.apiUintVars[keccak256("totalTip")] = _request.apiUintVars[keccak256("totalTip")].add(_tip); } //Set _payout for the submitted request uint256 _payout = _request.apiUintVars[keccak256("totalTip")]; //If there is no current request being mined //then set the currentRequestId to the requestid of the requestData or addtip requestId submitted, // the totalTips to the payout/tip submitted, and issue a new mining challenge if (self.uintVars[keccak256("currentRequestId")] == 0) { _request.apiUintVars[keccak256("totalTip")] = 0; self.uintVars[keccak256("currentRequestId")] = _requestId; self.uintVars[keccak256("currentTotalTips")] = _payout; self.currentChallenge = keccak256(abi.encodePacked(_payout, self.currentChallenge, blockhash(block.number - 1))); // Save hash for next proof emit NewChallenge( self.currentChallenge, self.uintVars[keccak256("currentRequestId")], self.uintVars[keccak256("difficulty")], self.requestDetails[self.uintVars[keccak256("currentRequestId")]].apiUintVars[keccak256("granularity")], self.requestDetails[self.uintVars[keccak256("currentRequestId")]].queryString, self.uintVars[keccak256("currentTotalTips")] ); } else { //If there is no OnDeckRequestId //then replace/add the requestId to be the OnDeckRequestId, queryHash and OnDeckTotalTips(current highest payout, aside from what //is being currently mined) if (_payout > self.requestDetails[onDeckRequestId].apiUintVars[keccak256("totalTip")] || (onDeckRequestId == 0)) { //let everyone know the next on queue has been replaced emit NewRequestOnDeck(_requestId, _request.queryString, _request.queryHash, _payout); } //if the request is not part of the requestQ[51] array //then add to the requestQ[51] only if the _payout/tip is greater than the minimum(tip) in the requestQ[51] array if (_request.apiUintVars[keccak256("requestQPosition")] == 0) { uint256 _min; uint256 _index; (_min, _index) = Utilities.getMin(self.requestQ); //we have to zero out the oldOne //if the _payout is greater than the current minimum payout in the requestQ[51] or if the minimum is zero //then add it to the requestQ array aand map its index information to the requestId and the apiUintvars if (_payout > _min || _min == 0) { self.requestQ[_index] = _payout; self.requestDetails[self.requestIdByRequestQIndex[_index]].apiUintVars[keccak256("requestQPosition")] = 0; self.requestIdByRequestQIndex[_index] = _requestId; _request.apiUintVars[keccak256("requestQPosition")] = _index; } // else if the requestid is part of the requestQ[51] then update the tip for it } else if (_tip > 0) { self.requestQ[_request.apiUintVars[keccak256("requestQPosition")]] += _tip; } } } } /** * @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 { using SafeMath for uint256; using TellorDispute for TellorStorage.TellorStorageStruct; using TellorLibrary for TellorStorage.TellorStorageStruct; using TellorStake for TellorStorage.TellorStorageStruct; using TellorTransfer for TellorStorage.TellorStorageStruct; TellorStorage.TellorStorageStruct tellor; /*Functions*/ /*This is a cheat for demo purposes, will delete upon actual launch*/ /*function theLazyCoon(address _address, uint _amount) public { tellor.theLazyCoon(_address,_amount); }*/ /** * @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 Allows for a fork to be proposed * @param _propNewTellorAddress address for new proposed Tellor */ function proposeFork(address _propNewTellorAddress) external { tellor.proposeFork(_propNewTellorAddress); } /** * @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 Request to retreive value from oracle based on timestamp. The tip is not required to be * greater than 0 because there are no tokens in circulation for the initial(genesis) request * @param _c_sapi string API being requested be mined * @param _c_symbol is the short string symbol for the api request * @param _granularity is the number of decimals miners should include on the submitted value * @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 requestData(string calldata _c_sapi, string calldata _c_symbol, uint256 _granularity, uint256 _tip) external { tellor.requestData(_c_sapi, _c_symbol, _granularity, _tip); } /** * @dev Proof of work is called by the miner when they submit the solution (proof of work and value) * @param _nonce uint submitted by miner * @param _requestId the apiId being mined * @param _value of api query */ function submitMiningSolution(string calldata _nonce, uint256 _requestId, uint256 _value) external { tellor.submitMiningSolution(_nonce, _requestId, _value); } /** * @dev Allows the current owner to propose transfer control of the contract to a * newOwner and the ownership is pending until the new owner calls the claimOwnership * function * @param _pendingOwner The address to transfer ownership to. */ function proposeOwnership(address payable _pendingOwner) external { tellor.proposeOwnership(_pendingOwner); } /** * @dev Allows the new owner to claim control of the contract */ function claimOwnership() external { tellor.claimOwnership(); } /** * @dev This function allows miners to deposit their stake. */ function depositStake() external { tellor.depositStake(); } /** * @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 */ function requestStakingWithdraw() external { tellor.requestStakingWithdraw(); } /** * @dev This function allows users to withdraw their stake after a 7 day waiting period from request */ function withdrawStake() external { tellor.withdrawStake(); } /** * @dev This function approves a _spender an _amount of tokens to use * @param _spender address * @param _amount amount the spender is being approved for * @return true if spender appproved successfully */ function approve(address _spender, uint256 _amount) external returns (bool) { return tellor.approve(_spender, _amount); } /** * @dev Allows for a transfer of tokens to _to * @param _to The address to send tokens to * @param _amount The amount of tokens to send * @return true if transfer is successful */ function transfer(address _to, uint256 _amount) external returns (bool) { return tellor.transfer(_to, _amount); } /** * @dev Sends _amount tokens to _to from _from on the condition it * is approved by _from * @param _from The address holding the tokens being transferred * @param _to The address of the recipient * @param _amount The amount of tokens to be transferred * @return True if the transfer was successful */ function transferFrom(address _from, address _to, uint256 _amount) external returns (bool) { return tellor.transferFrom(_from, _to, _amount); } /** * @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 Get the name of the token @return string of the token name/
function getName(TellorStorage.TellorStorageStruct storage self) internal pure returns (string memory) { return "Tellor Tributes"; }
12,861,464
[ 1, 967, 326, 508, 434, 326, 1147, 327, 533, 434, 326, 1147, 508, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1723, 12, 21009, 280, 3245, 18, 21009, 280, 3245, 3823, 2502, 365, 13, 2713, 16618, 1135, 261, 1080, 3778, 13, 288, 203, 3639, 327, 315, 21009, 280, 840, 495, 993, 14432, 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 ]
./partial_match/44787/0x7be4cd6b1f6f30302a9E325cd76ac09B2e667B4e/sources/planbV3_flattened.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 Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; } 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 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; } event lp(string test); 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("2", 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("2", 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("3", 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("3", 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("4", 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("4", 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 {} ) internal virtual {} }
16,956,396
[ 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, 1772, 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, 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, 203, 97, 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, 2078, 3088, 1283, 1435, 1071, 1476, 5024, 3849, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 389, 4963, 3088, 1283, 31, 203, 565, 289, 203, 203, 565, 445, 11013, 951, 12, 2867, 2236, 13, 1071, 1476, 5024, 3849, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 389, 70, 26488, 63, 4631, 15533, 203, 565, 289, 203, 203, 565, 2 ]
./full_match/1/0x60eEC879cd31e47347058048433D9E381F510606/sources/contracts/ommf/ommf_token/ommf.sol
* @notice Moves `_amount` tokens from the caller's account to the `_recipient` account. @return a boolean value indicating whether the operation succeeded. Emits a `Transfer` event. Emits a `TransferShares` event. Requirements: - `_recipient` cannot be the zero address. - the caller must have a balance of at least `_amount`. - the contract must not be paused. @dev The `_amount` argument is the amount of tokens, not shares./
function transfer(address _recipient, uint256 _amount) public returns (bool) { _transfer(msg.sender, _recipient, _amount); return true; }
16,405,046
[ 1, 19297, 1375, 67, 8949, 68, 2430, 628, 326, 4894, 1807, 2236, 358, 326, 1375, 67, 20367, 68, 2236, 18, 327, 279, 1250, 460, 11193, 2856, 326, 1674, 15784, 18, 7377, 1282, 279, 1375, 5912, 68, 871, 18, 7377, 1282, 279, 1375, 5912, 24051, 68, 871, 18, 29076, 30, 300, 1375, 67, 20367, 68, 2780, 506, 326, 3634, 1758, 18, 300, 326, 4894, 1297, 1240, 279, 11013, 434, 622, 4520, 1375, 67, 8949, 8338, 300, 326, 6835, 1297, 486, 506, 17781, 18, 225, 1021, 1375, 67, 8949, 68, 1237, 353, 326, 3844, 434, 2430, 16, 486, 24123, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 7412, 12, 2867, 389, 20367, 16, 2254, 5034, 389, 8949, 13, 1071, 1135, 261, 6430, 13, 288, 203, 565, 389, 13866, 12, 3576, 18, 15330, 16, 389, 20367, 16, 389, 8949, 1769, 203, 565, 327, 638, 31, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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; import "../Upgradability/StorageConsumer.sol"; /** * @title ActivatableRegistry * @dev Contract for creating a registry of activatable entries */ contract ActivatableRegistry is StorageConsumer { /** * @dev Event for when an entry is activated * @param entryId The ID of the entry that was activated */ event Activate(uint256 entryId); /** * @dev Event for when an entry is deactivated * @param entryId The ID of the entry that was deactivated */ event Deactivate(uint256 entryId); /** * @dev Creates a registry of activatable entries * @param storage_ The BaseStorage contract that stores ActivatableRegistry's state */ function ActivatableRegistry(BaseStorage storage_) StorageConsumer(storage_) public {} /** * @dev Check if an entry is active * @param _entryId The ID of the entry * @return true if the entry is active */ function active(uint256 _entryId) public view returns (bool) { return _storage.getBool(keccak256("activeStatus", _entryId)); } /** * @dev Activates a given entry * @param _entryId The ID of the entry to grant approval for. */ function activate(uint256 _entryId) public { require(checkEntryOwnership(_entryId)); require(!active(_entryId)); setActiveStatus(_entryId, true); Activate(_entryId); } /** * @dev Deactivates a given entry * @param _entryId The ID of the entry to revoke approval for. */ function deactivate(uint256 _entryId) public { require(checkEntryOwnership(_entryId)); require(active(_entryId)); setActiveStatus(_entryId, false); Deactivate(_entryId); } /** * @dev Sets the entry's status to _approvalStatus * @param _entryId The ID of the entry * @param _approvalStatus The status that will be set */ function setActiveStatus(uint256 _entryId, bool _approvalStatus) internal { _storage.setBool(keccak256("activeStatus", _entryId), _approvalStatus); } /** * @dev Checks if _entryId has entry ownership * @param _entryId An id associated with entry * @return true if entry id has entry ownership */ function checkEntryOwnership(uint256 _entryId) private view returns (bool); }
* @dev Activates a given entry @param _entryId The ID of the entry to grant approval for./
function activate(uint256 _entryId) public { require(checkEntryOwnership(_entryId)); require(!active(_entryId)); setActiveStatus(_entryId, true); Activate(_entryId); }
12,990,829
[ 1, 12241, 815, 279, 864, 1241, 225, 389, 4099, 548, 1021, 1599, 434, 326, 1241, 358, 7936, 23556, 364, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 10235, 12, 11890, 5034, 389, 4099, 548, 13, 1071, 288, 203, 565, 2583, 12, 1893, 1622, 5460, 12565, 24899, 4099, 548, 10019, 203, 565, 2583, 12, 5, 3535, 24899, 4099, 548, 10019, 203, 203, 565, 20669, 1482, 24899, 4099, 548, 16, 638, 1769, 203, 203, 565, 30936, 24899, 4099, 548, 1769, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity >=0.6.0 <0.7.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } /** * @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); /// Only for GHT token function transferOwnership(address newOwner) external; function setLockAmount(address account, uint256 amount) external returns (bool); function increaseLockAmount(address account, uint256 addedAmount) external returns (bool); function decreaseLockAmount(address account, uint256 subtractedAmount) external returns (bool); function unlockAmount(address account) external returns (bool); } /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return _msgSender() == _owner; } /** * @dev 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 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 Ownable { bool private _paused; address private _pauser; /** * @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); /** * @dev Emitted when the pauser is transferred by a owner. */ event PauserTransferred(address indexed previousPauser, address indexed newPauser); /** * @dev Initializes the contract setting the deployer as the initial pauser. * * @dev Initializes the contract in unpaused state. Assigns the Pauser role * to the deployer. */ constructor (address pauser) internal { _pauser = pauser; _paused = false; emit PauserTransferred(address(0), pauser); } /** * @dev Returns the address of the current pauser. */ function pauser() public view returns (address) { return _pauser; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyPauser() { require(isPauser(), "Pausable: caller is not the pauser"); _; } /** * @dev Returns true if the caller is the current pauser. */ function isPauser() public view returns (bool) { return _msgSender() == _pauser; } /** * @dev Transfers pauser of the contract to a new account (`newPauser`). * Can only be called by the current owner. */ function setNewPauser(address newPauser) public virtual onlyOwner { _transferPauser(newPauser); } /** * @dev Transfers pauser of the contract to a new account (`newPauser`). */ function _transferPauser(address newPauser) internal virtual { require(newPauser != address(0), "Pausable: new pauser is the zero address"); emit PauserTransferred(_pauser, newPauser); _pauser = newPauser; } /** * @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()); } } /** * @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; } } contract GHTCrowdSale is Pausable{ using SafeMath for uint256; IERC20 public ght; uint256 public minimumFee = 0.001 ether; uint32 public rate = 10**5; // 1 e = 100000 token constructor (address pauser, address _ght) public Ownable() Pausable(pauser){ ght = IERC20(_ght); } function setYourTokenAddress(address _yourTokenAddress) external onlyOwner { ght = IERC20(_yourTokenAddress); } function setMinimumFee(uint256 _newFee) external onlyOwner { minimumFee = _newFee; } function setRate(uint32 _newRate) external onlyOwner { rate = _newRate; } function buyToken() external payable whenNotPaused { require(msg.value >= minimumFee); address msgSender = _msgSender(); uint256 tokens = msg.value.mul(rate); ght.transfer(msgSender, tokens); ght.increaseLockAmount(msgSender,tokens); } receive() external payable whenNotPaused { require(msg.value >= minimumFee); address msgSender = _msgSender(); uint256 tokens = msg.value.mul(rate); ght.transfer(msgSender, tokens); ght.increaseLockAmount(msgSender,tokens); } function withdraw() external onlyOwner { address payable msgSender = _msgSender(); msgSender.transfer(address(this).balance); } function withdrawToken(address _token) external onlyOwner { IERC20 token = IERC20(_token); address msgSender = _msgSender(); token.transfer(msgSender, token.balanceOf(address(this))); } /// For token owner /** * @dev Set the user's balance locked amount. * Only call when this contract is the ownership of token contract. */ function setBackTokenContractOwnership(address Owner) public onlyOwner { ght.transferOwnership(Owner); } /** * @dev Set the user's balance locked amount. */ function setLockAmount(address account, uint256 amount) public onlyOwner { ght.setLockAmount(account, amount); } /** * @dev Increase the user's balance locked amount. */ function increaseLockAmount(address account, uint256 addedAmount) public onlyOwner { ght.increaseLockAmount(account, addedAmount); } /** * @dev Decreas the user's balance locked amount. */ function decreaseLockAmount(address account, uint256 subtractedAmount) public onlyOwner { ght.decreaseLockAmount(account, subtractedAmount); } /** * @dev Unlock user's balance. */ function unlockAmount(address account) public onlyOwner { ght.unlockAmount(account); } }
* @dev Transfers pauser of the contract to a new account (`newPauser`)./
function _transferPauser(address newPauser) internal virtual { require(newPauser != address(0), "Pausable: new pauser is the zero address"); emit PauserTransferred(_pauser, newPauser); _pauser = newPauser; }
1,437,125
[ 1, 1429, 18881, 6790, 1355, 434, 326, 6835, 358, 279, 394, 2236, 21863, 2704, 16507, 1355, 68, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 13866, 16507, 1355, 12, 2867, 394, 16507, 1355, 13, 2713, 5024, 288, 203, 3639, 2583, 12, 2704, 16507, 1355, 480, 1758, 12, 20, 3631, 315, 16507, 16665, 30, 394, 6790, 1355, 353, 326, 3634, 1758, 8863, 203, 3639, 3626, 21800, 1355, 1429, 4193, 24899, 8774, 1355, 16, 394, 16507, 1355, 1769, 203, 3639, 389, 8774, 1355, 273, 394, 16507, 1355, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /**************************************** * @author: squeebo_nft * * @team: GoldenX * **************************************** * Blimpie-ERC721 provides low-gas * * mints + transfers * ****************************************/ import './Blimpie/Delegated.sol'; import './Blimpie/ERC721EnumerableB.sol'; import "@openzeppelin/contracts/utils/Strings.sol"; import "@openzeppelin/contracts/finance/PaymentSplitter.sol"; interface IERC721Proxy{ function balanceOf( address account ) external view returns ( uint quantity ); function ownerOf( uint tokenId ) external view returns ( address owner ); } interface IPPL20{ function burnFromAccount( address account, uint pineapples ) external; function burnFromTokens( address[] calldata tokenContracts, uint[] calldata tokenIds, uint pineapples ) external; } contract SupLadies is Delegated, ERC721EnumerableB, PaymentSplitter { using Strings for uint; uint public MAX_ORDER = 19; uint public MAX_SUPPLY = 3914; uint public MAX_VOUCHERS = 1957; uint public ETH_PRICE = 0.1957 ether; uint public PPL_PRICE = 19.57 ether; bool public isMintActive = false; bool public isPineapplesActive = false; bool public isVoucherMintActive = false; bool public isVoucherUseActive = false; address public ahmcAddress = 0x61DB9Dde04F78fD55B0B4331a3d148073A101850; address public artwAddress = 0x22d202872950782012baC53346EE3DaE3D78E0CB; address public pineapplesAddress = 0x3e51F6422e41915e96A0808d21Babb83bcd278e5; mapping(address => uint) public vouchers; uint public voucherCount; string private _tokenURIPrefix; string private _tokenURISuffix; address[] private addressList = [ 0x13d86B7a637B9378d3646FA50De24e4e8fd78393, 0xc9241a5e35424a927536D0cA30C4687852402bCB, 0xB7edf3Cbb58ecb74BdE6298294c7AAb339F3cE4a ]; uint[] private shareList = [ 57, 35, 8 ]; constructor() Delegated() ERC721B("SupLadies", "SL", 0) PaymentSplitter( addressList, shareList ){ } //external function tokenURI(uint tokenId) external view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); return string(abi.encodePacked(_tokenURIPrefix, tokenId.toString(), _tokenURISuffix)); } fallback() external payable {} function mint( uint quantity ) external payable { require( isMintActive, "ETH sale is not active" ); require( quantity <= MAX_ORDER, "Order too big" ); require( msg.value >= ETH_PRICE * quantity, "Ether sent is not correct" ); uint256 supply = totalSupply(); require( supply + quantity <= MAX_SUPPLY, "Mint/order exceeds supply" ); for(uint i; i < quantity; ++i){ _safeMint( msg.sender, supply++, "" ); } } function mintWithPineapplesAccount( uint quantity ) external { require( isPineapplesActive, "Pineapple sale is not active" ); require( quantity <= MAX_ORDER, "Order too big" ); uint256 supply = totalSupply(); require( supply + quantity <= MAX_SUPPLY, "Order exceeds supply" ); _requireBalances(); uint totalPineapples = PPL_PRICE * quantity; IPPL20( pineapplesAddress ).burnFromAccount( msg.sender, totalPineapples); for(uint i; i < quantity; ++i){ _safeMint( msg.sender, supply++, "" ); } } function mintWithPineapplesTokens( uint quantity, address[] calldata tokenContracts, uint[] calldata tokenIds ) external { require( isPineapplesActive, "Pineapple sale is not active" ); require( quantity <= MAX_ORDER, "Order too big" ); uint256 supply = totalSupply(); require( supply + quantity <= MAX_SUPPLY, "Order exceeds supply" ); _requireBalances(); _requireOwnership( tokenContracts, tokenIds ); uint totalPineapples = PPL_PRICE * quantity; IPPL20( pineapplesAddress ).burnFromTokens(tokenContracts, tokenIds, totalPineapples); for(uint i; i < quantity; ++i){ _safeMint( msg.sender, supply++, "" ); } } function mintVouchersFromAccount( uint quantity ) external { require( isVoucherMintActive, "Voucher sale is not active" ); require( quantity <= MAX_ORDER, "Order too big" ); uint256 supply = totalSupply(); require( supply + quantity <= MAX_SUPPLY, "Order exceeds supply" ); require( voucherCount + quantity <= MAX_VOUCHERS, "Order exceeds supply" ); _requireBalances(); uint totalPineapples = PPL_PRICE * quantity; IPPL20( pineapplesAddress ).burnFromAccount( msg.sender, totalPineapples); voucherCount += quantity; vouchers[ msg.sender ] += quantity; } function mintVouchersFromTokens( uint quantity, address[] calldata tokenContracts, uint[] calldata tokenIds ) external { require( isVoucherMintActive, "Voucher sale is not active" ); require( quantity <= MAX_ORDER, "Order too big" ); uint256 supply = totalSupply(); require( supply + quantity <= MAX_SUPPLY, "Order exceeds supply" ); require( voucherCount + quantity <= MAX_VOUCHERS, "Order exceeds supply" ); _requireBalances(); _requireOwnership( tokenContracts, tokenIds ); uint totalPineapples = PPL_PRICE * quantity; IPPL20( pineapplesAddress ).burnFromTokens(tokenContracts, tokenIds, totalPineapples); voucherCount += quantity; vouchers[ msg.sender ] += quantity; } function useVouchers( uint quantity ) external { require( isVoucherUseActive, "Voucher mint is not active" ); require( quantity <= MAX_ORDER, "Order too big" ); uint256 supply = totalSupply(); require( supply + quantity <= MAX_SUPPLY, "Order exceeds supply" ); require( quantity <= vouchers[ msg.sender ], "Order exceeds vouchers" ); voucherCount -= quantity; vouchers[ msg.sender ] -= quantity; for(uint i = 0; i < quantity; ++i){ _safeMint( msg.sender, supply++, "" ); } } //onlyDelegates function mintTo(uint[] calldata quantity, address[] calldata recipient) external payable onlyDelegates{ require(quantity.length == recipient.length, "Must provide equal quantities and recipients" ); uint totalQuantity = 0; uint256 supply = totalSupply(); for(uint i = 0; i < quantity.length; ++i){ totalQuantity += quantity[i]; } require( supply + totalQuantity < MAX_SUPPLY, "Mint/order exceeds supply" ); for(uint i; i < recipient.length; ++i){ for(uint j; j < quantity[i]; ++j){ _safeMint( recipient[i], supply++, "" ); } } } function mintVouchersTo(uint[] calldata quantity, address[] calldata recipient) external payable onlyDelegates{ require(quantity.length == recipient.length, "Must provide equal quantities and recipients" ); uint totalQuantity = 0; uint256 supply = totalSupply(); for(uint i = 0; i < quantity.length; ++i){ totalQuantity += quantity[i]; } require( supply + totalQuantity < MAX_VOUCHERS, "Vouchers exceeds supply" ); for(uint i; i < recipient.length; ++i){ voucherCount += quantity[i]; vouchers[ recipient[i] ] += quantity[i]; } } function setActive(bool isActive_, bool isPineapplesActive_, bool isVoucherMintActive_, bool isVoucherUseActive_) external onlyDelegates{ require( isMintActive != isActive_ || isPineapplesActive != isPineapplesActive_ || isVoucherMintActive != isVoucherMintActive_ || isVoucherUseActive != isVoucherUseActive_, "New value matches old" ); isMintActive = isActive_; isPineapplesActive = isPineapplesActive_; isVoucherMintActive = isVoucherMintActive_; isVoucherUseActive = isVoucherUseActive_; } function setBaseURI(string calldata prefix, string calldata suffix) external onlyDelegates{ _tokenURIPrefix = prefix; _tokenURISuffix = suffix; } function setContracts(address pineapplesAddress_, address ahmcAddress_, address artwAddress_ ) external onlyDelegates { pineapplesAddress = pineapplesAddress_; ahmcAddress = ahmcAddress_; artwAddress = artwAddress_; } function setMaxSupply(uint maxOrder, uint maxSupply, uint maxVouchers) external onlyDelegates{ require( MAX_ORDER != maxOrder || MAX_SUPPLY != maxSupply || MAX_VOUCHERS != maxVouchers, "New value matches old" ); require( maxSupply >= totalSupply(), "Specified supply is lower than current balance" ); MAX_ORDER = maxOrder; MAX_SUPPLY = maxSupply; MAX_VOUCHERS = maxVouchers; } function setPrice(uint ethPrice, uint pplPrice ) external onlyDelegates{ require( ETH_PRICE != ethPrice || PPL_PRICE != pplPrice, "New value matches old" ); ETH_PRICE = ethPrice; PPL_PRICE = pplPrice; } //private function _requireBalances() private view { uint ahmc = IERC721( ahmcAddress ).balanceOf( msg.sender ); if( ahmc >= 2 ) return; uint artw = IERC721( artwAddress ).balanceOf( msg.sender ); if( artw >= 11 ) return; if( ahmc > 0 && artw >= 5 ) return; revert( "Not enough AHMC/ARTW tokens" ); } function _requireOwnership( address[] calldata tokenContracts, uint[] calldata tokenIds ) private view { for( uint i; i < tokenContracts.length; ++i ){ require( msg.sender == IERC721( tokenContracts[i] ).ownerOf( tokenIds[i] ), "Invalid owner of token" ); } } } // SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.8.0; interface IBatch { function isOwnerOf( address account, uint[] calldata tokenIds ) external view returns( bool ); function transferBatch( address from, address to, uint[] calldata tokenIds, bytes calldata data ) external; function walletOfOwner( address account ) external view returns( uint[] memory ); } // SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.8.0; import "./ERC721B.sol"; import "./IBatch.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol"; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721EnumerableB is ERC721B, IBatch, IERC721Enumerable { mapping(address => uint[]) internal _balances; function balanceOf(address owner) public view virtual override(ERC721B,IERC721) returns (uint) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner].length; } function isOwnerOf( address account, uint[] calldata tokenIds ) external view override returns( bool ){ for(uint i; i < tokenIds.length; ++i ){ if( _owners[ tokenIds[i] ] != account ) return false; } return true; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721B) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint index) public view virtual override returns (uint tokenId) { require(index < ERC721B.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _balances[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint) { return _owners.length - _offset; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint index) public view virtual override returns (uint) { require(index < totalSupply(), "ERC721Enumerable: global index out of bounds"); return index + _offset; } function walletOfOwner( address account ) external view override returns( uint[] memory ){ return _balances[ account ]; } function transferBatch( address from, address to, uint[] calldata tokenIds, bytes calldata data ) external override{ for(uint i; i < tokenIds.length; ++i ){ safeTransferFrom( from, to, tokenIds[i], data ); } } //internal function _beforeTokenTransfer( address from, address to, uint tokenId ) internal override virtual { address zero = address(0); if( from != zero ){ //find this token and remove it uint length = _balances[from].length; for( uint i; i < length; ++i ){ if( _balances[from][i] == tokenId ){ _balances[from][i] = _balances[from][length - 1]; _balances[from].pop(); break; } } } if( to != zero ) _balances[to].push( tokenId ); } } // SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.8.0; /******************** * @author: Squeebo * ********************/ import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/utils/Context.sol"; import "@openzeppelin/contracts/utils/introspection/ERC165.sol"; abstract contract ERC721B is Context, ERC165, IERC721, IERC721Metadata { using Address for address; string private _name; string private _symbol; uint internal _offset; // Mapping from token ID to owner address address[] internal _owners; // Mapping from token ID to approved address mapping(uint => 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_, uint offset) { _name = name_; _symbol = symbol_; _offset = offset; for(uint i; i < _offset; ++i ){ _owners.push(address(0)); } } //public function balanceOf(address owner) public view virtual override returns (uint) { require(owner != address(0), "ERC721: balance query for the zero address"); uint count = 0; uint length = _owners.length; for( uint i = 0; i < length; ++i ){ if( owner == _owners[i] ) ++count; } return count; } function name() public view virtual override returns (string memory) { return _name; } function next() public view returns( uint ){ return _owners.length; } function ownerOf(uint tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } function symbol() public view virtual override returns (string memory) { return _symbol; } function approve(address to, uint tokenId) public virtual override { address owner = ERC721B.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); } function getApproved(uint tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } function transferFrom( address from, address to, uint 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, uint tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } //internal function _safeTransfer( address from, address to, uint tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } function _exists(uint tokenId) internal view virtual returns (bool) { return tokenId < _owners.length && _owners[tokenId] != address(0); } function _isApprovedOrOwner(address spender, uint tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721B.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } function _safeMint(address to, uint tokenId) internal virtual { _safeMint(to, tokenId, ""); } function _safeMint( address to, uint tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } function _mint(address to, uint 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); _owners.push(to); emit Transfer(address(0), to, tokenId); } function _burn(uint tokenId) internal virtual { address owner = ERC721B.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _owners[tokenId] = address(0); emit Transfer(owner, address(0), tokenId); } function _transfer( address from, address to, uint tokenId ) internal virtual { require(ERC721B.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); _owners[tokenId] = to; emit Transfer(from, to, tokenId); } function _approve(address to, uint tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721B.ownerOf(tokenId), to, tokenId); } function _checkOnERC721Received( address from, address to, uint 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; } } function _beforeTokenTransfer( address from, address to, uint tokenId ) internal virtual {} } // SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.8.0; /******************** * @author: Squeebo * ********************/ import "@openzeppelin/contracts/access/Ownable.sol"; contract Delegated is Ownable{ mapping(address => bool) internal _delegates; constructor(){ _delegates[owner()] = true; } modifier onlyDelegates { require(_delegates[msg.sender], "Invalid delegate" ); _; } //onlyOwner function isDelegate( address addr ) external view onlyOwner returns ( bool ){ return _delegates[addr]; } function setDelegate( address addr, bool isDelegate_ ) external onlyOwner{ _delegates[addr] = isDelegate_; } function transferOwnership(address newOwner) public virtual override onlyOwner { _delegates[newOwner] = true; super.transferOwnership( newOwner ); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Address.sol"; import "../utils/Context.sol"; import "../utils/math/SafeMath.sol"; /** * @title PaymentSplitter * @dev This contract allows to split Ether payments among a group of accounts. The sender does not need to be aware * that the Ether will be split in this way, since it is handled transparently by the contract. * * The split can be in equal parts or in any other arbitrary proportion. The way this is specified is by assigning each * account to a number of shares. Of all the Ether that this contract receives, each account will then be able to claim * an amount proportional to the percentage of total shares they were assigned. * * `PaymentSplitter` follows a _pull payment_ model. This means that payments are not automatically forwarded to the * accounts but kept in this contract, and the actual transfer is triggered as a separate step by calling the {release} * function. */ contract PaymentSplitter is Context { event PayeeAdded(address account, uint256 shares); event PaymentReleased(address to, uint256 amount); event PaymentReceived(address from, uint256 amount); uint256 private _totalShares; uint256 private _totalReleased; mapping(address => uint256) private _shares; mapping(address => uint256) private _released; address[] private _payees; /** * @dev Creates an instance of `PaymentSplitter` where each account in `payees` is assigned the number of shares at * the matching position in the `shares` array. * * All addresses in `payees` must be non-zero. Both arrays must have the same non-zero length, and there must be no * duplicates in `payees`. */ constructor(address[] memory payees, uint256[] memory shares_) payable { require(payees.length == shares_.length, "PaymentSplitter: payees and shares length mismatch"); require(payees.length > 0, "PaymentSplitter: no payees"); for (uint256 i = 0; i < payees.length; i++) { _addPayee(payees[i], shares_[i]); } } /** * @dev The Ether received will be logged with {PaymentReceived} events. Note that these events are not fully * reliable: it's possible for a contract to receive Ether without triggering this function. This only affects the * reliability of the events, and not the actual splitting of Ether. * * To learn more about this see the Solidity documentation for * https://solidity.readthedocs.io/en/latest/contracts.html#fallback-function[fallback * functions]. */ receive() external payable virtual { emit PaymentReceived(_msgSender(), msg.value); } /** * @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 payee. */ function released(address account) public view returns (uint256) { return _released[account]; } /** * @dev Getter for the address of the payee number `index`. */ function payee(uint256 index) public view returns (address) { return _payees[index]; } /** * @dev Triggers a transfer to `account` of the amount of Ether they are owed, according to their percentage of the * total shares and their previous withdrawals. */ function release(address payable account) public virtual { require(_shares[account] > 0, "PaymentSplitter: account has no shares"); uint256 totalReceived = address(this).balance + _totalReleased; uint256 payment = (totalReceived * _shares[account]) / _totalShares - _released[account]; require(payment != 0, "PaymentSplitter: account is not due payment"); _released[account] = _released[account] + payment; _totalReleased = _totalReleased + payment; Address.sendValue(account, payment); emit PaymentReleased(account, payment); } /** * @dev Add a new payee to the contract. * @param account The address of the payee to add. * @param shares_ The number of shares owned by the payee. */ function _addPayee(address account, uint256 shares_) private { require(account != address(0), "PaymentSplitter: account is the zero address"); require(shares_ > 0, "PaymentSplitter: shares are 0"); require(_shares[account] == 0, "PaymentSplitter: account already has shares"); _payees.push(account); _shares[account] = shares_; _totalShares = _totalShares + shares_; emit PayeeAdded(account, shares_); } } // 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); } }
* @dev See {IERC165-supportsInterface}./
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721B) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); }
338,776
[ 1, 9704, 288, 45, 654, 39, 28275, 17, 28064, 1358, 5496, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 6146, 1358, 12, 3890, 24, 1560, 548, 13, 1071, 1476, 5024, 3849, 12, 45, 654, 39, 28275, 16, 4232, 39, 27, 5340, 38, 13, 1135, 261, 6430, 13, 288, 203, 3639, 327, 1560, 548, 422, 618, 12, 45, 654, 39, 27, 5340, 3572, 25121, 2934, 5831, 548, 747, 2240, 18, 28064, 1358, 12, 5831, 548, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x716744A30CD4bf6e4cfCCf7598f724BE5172d0B9/sources/wallet.sol
@dev Confirm pending whitelist addition. Require that the whitelist addition has been submitted. Require that confirmation hash and the hash of the pending whitelist addition match Whitelist pending addresses.
function confirmWhitelistAddition(bytes32 _hash) external onlyController { require(submittedWhitelistAddition, "whitelist addition has not been submitted"); require(_hash == pendingWhitelistHash(_pendingWhitelistAddition), "hash of the pending whitelist addition do not match"); for (uint i = 0; i < _pendingWhitelistAddition.length; i++) { isWhitelisted[_pendingWhitelistAddition[i]] = true; } }
4,295,145
[ 1, 11269, 4634, 10734, 2719, 18, 12981, 716, 326, 10734, 2719, 711, 2118, 9638, 18, 12981, 716, 14296, 1651, 471, 326, 1651, 434, 326, 4634, 10734, 2719, 845, 3497, 7523, 4634, 6138, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 6932, 18927, 30296, 12, 3890, 1578, 389, 2816, 13, 3903, 1338, 2933, 288, 203, 3639, 2583, 12, 31575, 18927, 30296, 16, 315, 20409, 2719, 711, 486, 2118, 9638, 8863, 203, 203, 3639, 2583, 24899, 2816, 422, 4634, 18927, 2310, 24899, 9561, 18927, 30296, 3631, 315, 2816, 434, 326, 4634, 10734, 2719, 741, 486, 845, 8863, 203, 203, 3639, 364, 261, 11890, 277, 273, 374, 31, 277, 411, 389, 9561, 18927, 30296, 18, 2469, 31, 277, 27245, 288, 203, 5411, 353, 18927, 329, 63, 67, 9561, 18927, 30296, 63, 77, 13563, 273, 638, 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 ]
pragma solidity ^0.4.18; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @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; function Ownable() public { } /** * @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) internal onlyOwner { require(newOwner != address(0)); owner = newOwner; } } /** * @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 returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title PoSTokenStandard * @dev the interface of PoSTokenStandard */ contract PoSTokenStandard { uint256 public stakeStartTime; uint256 public stakeMinAge; uint256 public stakeMaxAge; function mine() public returns (bool); function coinAge(address who) public returns (uint256); function annualInterest() public returns (uint256); event Mine(address indexed _address, uint _reward); } contract CoinVila is ERC20,PoSTokenStandard,Ownable { using SafeMath for uint256; string public name = "CoinVila"; string public symbol = "VILA"; uint public decimals = 18; uint public chainStartTime; //chain start time uint public chainStartBlockNumber; //chain start block number uint public stakeStartTime; //stake start time uint public stakeMinAge = 3 days; // minimum age for coin age: 3D uint public stakeMaxAge = 90 days; // stake age of full weight: 90D uint public maxMintProofOfStake = 10**17; // default 10% annual interest uint public totalSupply; uint public maxTotalSupply = 44 * (10**6) * (10**uint256(decimals)); // 44 Mil uint public totalInitialSupply = 250 * (10**3) * (10**uint256(decimals)); // 250 K uint256 public INITIAL_SUPPLY = 250 * (10**3) * (10 ** uint256(decimals)); //250 K address public addressFundTeam = 0x5F7C2F8041cAB567c41708D5a89119F710322e3f; address public addressFundAirdrop = 0xba960ab8007B825Fa74682A61735FE3ECd653ee3; address public addressFundBounty = 0xdF96e49EC0983153B0Bf2125d60032Eb3685A457; address public addressFundPlatform = 0x65632770903989Ae84B49E9A758d7ADDA63697A3; address public addressFundHolder = 0xa198baaB6dD6D7023b184C450D64175d19bCB450; uint256 public amountFundTeam = 25 * (10**3) * (10**uint256(decimals)); uint256 public amountFundAirdrop = 120 * (10**3) * (10**uint256(decimals)); uint256 public amountFundBounty = 5 * (10**3) * (10**uint256(decimals)); uint256 public amountFundPlatform = 75 * (10**3) * (10**uint256(decimals)); uint256 public amountFundHolder = 25 * (10**3) * (10**uint256(decimals)); struct transferInStruct{ uint128 amount; uint64 time; } mapping(address => uint256) balances; mapping(address => mapping (address => uint256)) allowed; mapping(address => transferInStruct[]) transferIns; /** * @dev Fix for the ERC20 short address attack. */ modifier onlyPayloadSize(uint size) { require(msg.data.length >= size + 4); _; } modifier canPoSMint() { require(totalSupply < maxTotalSupply); _; } function CoinVila(address _owner) public { require(_owner != address(0)); owner = _owner; CoinVilaStart(); } function CoinVilaStart() private { uint64 _now = uint64(now); totalSupply = totalInitialSupply; chainStartTime = _now; chainStartBlockNumber = block.number; stakeStartTime = _now; balances[addressFundTeam] = amountFundTeam; transferIns[addressFundTeam].push(transferInStruct(uint128(amountFundTeam),_now)); balances[addressFundHolder] = amountFundHolder; transferIns[addressFundHolder].push(transferInStruct(uint128(amountFundHolder),_now)); balances[addressFundAirdrop] = amountFundAirdrop; transferIns[addressFundAirdrop].push(transferInStruct(uint128(amountFundAirdrop),_now)); balances[addressFundBounty] = amountFundBounty; transferIns[addressFundBounty].push(transferInStruct(uint128(amountFundBounty),_now)); balances[addressFundPlatform] = amountFundPlatform; transferIns[addressFundPlatform].push(transferInStruct(uint128(amountFundPlatform),_now)); } function transfer(address _to, uint256 _value) onlyPayloadSize(2 * 32) public returns (bool) { if(msg.sender == _to) return mine(); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); if(transferIns[msg.sender].length > 0) delete transferIns[msg.sender]; uint64 _now = uint64(now); transferIns[msg.sender].push(transferInStruct(uint128(balances[msg.sender]),_now)); transferIns[_to].push(transferInStruct(uint128(_value),_now)); return true; } function balanceOf(address _owner) public returns (uint256 balance) { return balances[_owner]; } function transferFrom(address _from, address _to, uint256 _value) onlyPayloadSize(3 * 32) public returns (bool) { require(_to != address(0)); var _allowance = allowed[_from][msg.sender]; balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); if(transferIns[_from].length > 0) delete transferIns[_from]; uint64 _now = uint64(now); transferIns[_from].push(transferInStruct(uint128(balances[_from]),_now)); transferIns[_to].push(transferInStruct(uint128(_value),_now)); return true; } function approve(address _spender, uint256 _value) public returns (bool) { require((_value == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public returns (uint256 remaining) { return allowed[_owner][_spender]; } function mine() canPoSMint public returns (bool) { if(balances[msg.sender] <= 0) return false; if(transferIns[msg.sender].length <= 0) return false; uint reward = getProofOfStakeReward(msg.sender); if(reward <= 0) return false; totalSupply = totalSupply.add(reward); balances[msg.sender] = balances[msg.sender].add(reward); delete transferIns[msg.sender]; transferIns[msg.sender].push(transferInStruct(uint128(balances[msg.sender]),uint64(now))); Mine(msg.sender, reward); return true; } function getBlockNumber() public view returns (uint blockNumber) { blockNumber = block.number.sub(chainStartBlockNumber); } function coinAge(address who) public returns (uint myCoinAge) { myCoinAge = getCoinAge(who,now); } /** * Year 1 300% 1,000,000 * Year 2 300% 4,000,000 * Year 3 50% 6,000,000 * Year 4 50% 9,000,000 * Year 5 50% 13,500,000 * Year 6 50% 21,000,000 * Year 7 50% 32,000,000 * Year 8 10% 36,000,000 * Year 9 10% 40,000,000 * Year 10 10% 44,000,000 */ function annualInterest() public returns(uint interest) { uint _now = now; interest = maxMintProofOfStake; if((_now.sub(stakeStartTime).div(1 years) == 0) || (_now.sub(stakeStartTime).div(1 years) == 1) ) { interest = (1650 * maxMintProofOfStake).div(100); } else if((_now.sub(stakeStartTime).div(1 years) == 2) || (_now.sub(stakeStartTime).div(1 years) == 3) || (_now.sub(stakeStartTime).div(1 years) == 4) || (_now.sub(stakeStartTime).div(1 years) == 5) || (_now.sub(stakeStartTime).div(1 years) == 6)){ interest = (435 * maxMintProofOfStake).div(100); } } function getProofOfStakeReward(address _address) internal view returns (uint) { require( (now >= stakeStartTime) && (stakeStartTime > 0) ); uint _now = now; uint _coinAge = getCoinAge(_address, _now); if(_coinAge <= 0) return 0; uint interest = maxMintProofOfStake; // Due to the high interest rate for the first two years, compounding should be taken into account. // Effective annual interest rate = (1 + (nominal rate / number of compounding periods)) ^ (number of compounding periods) - 1 if((_now.sub(stakeStartTime).div(1 years) == 0) || (_now.sub(stakeStartTime).div(1 years) == 1)) { // 1st, 2nd year effective annual interest rate is 300% when we select the stakeMaxAge (90 days) as the compounding period. interest = (1650 * maxMintProofOfStake).div(100); } else if ((_now.sub(stakeStartTime).div(1 years) == 2) || (_now.sub(stakeStartTime).div(1 years) == 3) || (_now.sub(stakeStartTime).div(1 years) == 4) || (_now.sub(stakeStartTime).div(1 years) == 5) || (_now.sub(stakeStartTime).div(1 years) == 6)) { // 3nd, 4nd, 5nd, 6nd, 7nd year effective annual interest rate is 50% when we select the stakeMaxAge (90 days) as the compounding period. interest = (435 * maxMintProofOfStake).div(100); } return (_coinAge * interest).div(365 * (10**decimals)); } function getCoinAge(address _address, uint _now) internal view returns (uint _coinAge) { if(transferIns[_address].length <= 0) return 0; for (uint i = 0; i < transferIns[_address].length; i++){ if( _now < uint(transferIns[_address][i].time).add(stakeMinAge) ) continue; uint nCoinSeconds = _now.sub(uint(transferIns[_address][i].time)); if( nCoinSeconds > stakeMaxAge ) nCoinSeconds = stakeMaxAge; _coinAge = _coinAge.add(uint(transferIns[_address][i].amount) * nCoinSeconds.div(1 days)); } } //function ownerSetStakeStartTime(uint timestamp) public { function ownerSetStakeStartTime(uint timestamp) public onlyOwner { require(stakeStartTime <= 0); stakeStartTime = timestamp; } /** * Peterson's Law Protection * Claim tokens */ function claimTokens() public onlyOwner { uint256 balance = balanceOf(this); transfer(owner, balance); Transfer(this, owner, balance); owner.transfer(this.balance); } }
default 10% annual interest
uint public maxMintProofOfStake = 10**17;
425,829
[ 1, 1886, 1728, 9, 8226, 1462, 16513, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 1071, 943, 49, 474, 20439, 951, 510, 911, 273, 1728, 636, 4033, 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 ]
./full_match/5/0x22c4d70aCaD043f964dcff5571E7Cf24e12D1De7/sources/contracts/Contract.sol
verifie si tout est bon
function createCampaign(address _owner, string memory _title, string memory _description, uint256 _target, uint256 _deadline, string memory _image) public returns (uint256) { Campaign storage campaign = campaigns[numberOfCampaigns]; require(campaign.deadline<block.timestamp, "La deadline ne peut pas etre avant aujourd\'hui"); campaign.owner=_owner; campaign.title=_title; campaign.description=_description; campaign.target=_target; campaign.deadline=_deadline; campaign.amountCollected=0; campaign.image=_image; numberOfCampaigns++; return numberOfCampaigns - 1; }
7,048,568
[ 1, 502, 704, 73, 7533, 358, 322, 4387, 324, 265, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 752, 13432, 12, 2867, 389, 8443, 16, 533, 3778, 389, 2649, 16, 533, 3778, 389, 3384, 16, 2254, 5034, 389, 3299, 16, 2254, 5034, 389, 22097, 1369, 16, 533, 3778, 389, 2730, 13, 1071, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 17820, 2502, 8965, 273, 8965, 87, 63, 2696, 951, 13432, 87, 15533, 203, 203, 3639, 2583, 12, 14608, 18, 22097, 1369, 32, 2629, 18, 5508, 16, 315, 30745, 14096, 1073, 2804, 322, 14699, 3393, 266, 1712, 970, 279, 11501, 477, 72, 3730, 76, 4881, 8863, 203, 203, 3639, 8965, 18, 8443, 33, 67, 8443, 31, 203, 3639, 8965, 18, 2649, 33, 67, 2649, 31, 203, 3639, 8965, 18, 3384, 33, 67, 3384, 31, 203, 3639, 8965, 18, 3299, 33, 67, 3299, 31, 203, 3639, 8965, 18, 22097, 1369, 33, 67, 22097, 1369, 31, 203, 3639, 8965, 18, 8949, 10808, 329, 33, 20, 31, 203, 3639, 8965, 18, 2730, 33, 67, 2730, 31, 203, 203, 3639, 7922, 13432, 87, 9904, 31, 203, 203, 3639, 327, 7922, 13432, 87, 300, 404, 31, 203, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "./interfaces/IERC20.sol"; import "./maths/SafeMath.sol"; import "./structures/PoolStruct.sol"; import "./libs/string.sol"; contract PeetStakingContract { using SafeMath for uint256; using strings for *; address private _poolManager; mapping(bytes32 => PoolStructure) private _pools; bytes32[] public allPoolsIndices; bytes32[] public activePoolsIndices; bytes32[] public endedPoolsIndices; constructor(address manager) { _poolManager = manager; } event LogNewPublishedPool( bytes32 pool_indice, bytes32 pool_name, bool state, uint256 amount_reward, uint256 participation, uint256 startDate, uint256 endDate ); event LogUpdatedPublishedPool( bytes32 pool_indice, bytes32 pool_name, bool state, uint256 amount_reward, uint256 participation, uint256 startDate, uint256 endDate ); event RewardReceivedFromPool( bytes32 pool_indice, uint256 amount_reward, address receiver, address output_asset ); function removeActivePoolIndexation(bytes32 indice) private { if (activePoolsIndices.length == 0) { return; } if (activePoolsIndices.length == 1) { delete activePoolsIndices; return; } bytes32[] memory newArray = new bytes32[](activePoolsIndices.length - 1); uint256 new_index = 0; for (uint256 i = 0; i < activePoolsIndices.length; i++) { if (_pools[activePoolsIndices[i]].pool_indice != indice) { newArray[new_index++] = activePoolsIndices[i]; } } activePoolsIndices = newArray; PoolStructure storage pool = _pools[indice]; // emit disabled pool event emit LogUpdatedPublishedPool( pool.pool_indice, pool.pool_name, pool.pool_active, pool.rewards_pool.amount_reward, pool.funds_pool.max_total_participation, pool.start_date, pool.end_date ); } function enableActivePoolIndexation(bytes32 indice, PoolStructure storage pool) private { activePoolsIndices.push(indice); // emit enabled pool event emit LogNewPublishedPool( pool.pool_indice, pool.pool_name, pool.pool_active, pool.rewards_pool.amount_reward, pool.funds_pool.max_total_participation, pool.start_date, pool.end_date ); } function addPoolToIndexation(bytes32 indice, PoolStructure storage pool) private { // for all pool history allPoolsIndices.push(indice); // save the indice key in case the pool is already active at publishment if (pool.pool_active) { enableActivePoolIndexation(indice, pool); } } function getTotalWalletPoolInputAmount (bytes32 indice, address addr) public view returns(uint256) { PoolStructure storage pool = _pools[indice]; PoolWallet storage wallet = pool._wallets[addr]; uint256 amountInPool = 0; for (uint256 i = 0; i < wallet.input_asset_amount.length; i++) { amountInPool += wallet.input_asset_amount[i]; } return amountInPool; } function updatePoolState(bytes32 indice, bool state) public { require( msg.sender == _poolManager, "Not authorized to update pool state" ); PoolStructure storage pool = _pools[indice]; if (state && !pool.pool_active) { enableActivePoolIndexation(indice, pool); } else if (!state && pool.pool_active) { removeActivePoolIndexation(indice); } pool.pool_active = state; } function depositInPool(bytes32 indice, uint256 amount) public { PoolStructure storage pool = _pools[indice]; require( pool.pool_active == true, "Pool selected isn't active" ); uint256 totalWalletPooled = getTotalWalletPoolInputAmount(indice, address(msg.sender)).add(amount); uint256 totalPoolInputAsset = pool.total_amount_input_pooled.add(amount); require( block.timestamp < pool.start_date, "Pool already started, you cant stake in this one!" ); require( totalPoolInputAsset <= pool.funds_pool.max_total_participation, "Max pool cap already reached, you cant join this pool" ); require( totalWalletPooled <= pool.funds_pool.max_wallet_participation, "Max wallet amount reached for this pool" ); IERC20 input_token = IERC20(address(pool.input_asset)); require( input_token.balanceOf(address(msg.sender)) >= amount, "Invalid funds to deposit in pools" ); require( input_token.transferFrom(msg.sender, address(this), amount) == true, "Error transferFrom on the contract" ); PoolWallet storage wallet = pool._wallets[address(msg.sender)]; wallet.input_asset_amount.push(amount); wallet.start_date_pooled.push(block.timestamp); pool.total_amount_input_pooled = totalPoolInputAsset; } function calculateAndSendReward(bytes32 indice, address from, uint256 inputAmount) private returns(uint256) { PoolStructure storage pool = _pools[indice]; uint256 weightPercent = inputAmount.mul(100).div(pool.funds_pool.max_wallet_participation).mul(10); uint256 rewardAmount = pool.rewards_pool.base_amount_reward * weightPercent / 10000; IERC20 output_token = IERC20(address(pool.output_asset)); require( output_token.balanceOf(address(this)) >= rewardAmount, "Invalid pool contract output funds" ); require( output_token.transfer(from, rewardAmount) == true, "Error transfer reward on the contract" ); pool.rewards_pool.amount_reward -= rewardAmount; // emit event received reward emit RewardReceivedFromPool(pool.pool_indice, rewardAmount, from, pool.output_asset); return rewardAmount; } function leftRewardsInPool(bytes32 indice) public view returns(uint256) { PoolStructure storage pool = _pools[indice]; return pool.rewards_pool.amount_reward; } function withdrawPoolRewardsUnconsumed(bytes32 indice) public { require( msg.sender == _poolManager, "Not authorized to withdraw pool reward funds" ); PoolStructure storage pool = _pools[indice]; require( pool.rewards_pool.amount_reward > 0, "No amount rewards left in the pool" ); require( block.timestamp > pool.end_date, "Pool end date isnt reached yet" ); IERC20 output_token = IERC20(address(pool.output_asset)); uint256 balanceToken = output_token.balanceOf(address(this)); uint256 withdrawalAmount = 0; // allow pool manager to retire unconsumed rewards from the total pool cap if (balanceToken < pool.rewards_pool.amount_reward) { withdrawalAmount = balanceToken; } else { withdrawalAmount = pool.rewards_pool.amount_reward; } require( output_token.transfer(_poolManager, withdrawalAmount) == true, "Error transfer on the contract" ); pool.rewards_pool.amount_reward = 0; } function withdrawFromPool(bytes32 indice) public returns (uint256) { PoolStructure storage pool = _pools[indice]; require( block.timestamp > pool.end_date, "Pool end date isnt reached yet" ); address sender = address(msg.sender); uint256 walletInputAmount = getTotalWalletPoolInputAmount(indice, sender); require ( walletInputAmount > 0, "No funds to withdraw" ); IERC20 input_token = IERC20(address(pool.input_asset)); require( input_token.balanceOf(address(this)) >= walletInputAmount, "Invalid funds in the pool" ); require( input_token.transfer(msg.sender, walletInputAmount) == true, "Error transfer on the contract" ); if (pool.pool_active) { removeActivePoolIndexation(pool.pool_indice); pool.pool_active = false; endedPoolsIndices.push(indice); } uint256 rewardAmount = calculateAndSendReward(indice, sender, walletInputAmount); // we reset the input amount just sent back PoolWallet storage wallet = pool._wallets[sender]; for (uint256 i = 0; i < wallet.input_asset_amount.length; i++) { wallet.input_asset_amount[i] = 0; } return rewardAmount; } function publishPool(bytes32 name, address in_asset, address out_asset, uint256 start_date, uint256 end_date, bool state_pool, uint256 amount_reward, uint max_wallet, uint max_total) public returns(bytes32) { require( msg.sender == _poolManager, "Not authorized to publish a new pool" ); IERC20 _reward_token = IERC20(address(out_asset)); require( _reward_token.balanceOf(address(this)) >= amount_reward, "Cant create this pool cause output asset rewards funds are too low" ); bytes32 pool_indice = keccak256(abi.encode(name, strings.uint2str(start_date), strings.uint2str(end_date))); // Pool base structure PoolStructure storage new_pool = _pools[pool_indice]; new_pool.pool_indice = pool_indice; new_pool.pool_name = name; new_pool.input_asset = in_asset; new_pool.output_asset = out_asset; new_pool.start_date = start_date; new_pool.end_date = end_date; new_pool.pool_active = state_pool; // Pool Rewards PoolRewards memory rewards; rewards.base_amount_reward = amount_reward; rewards.amount_reward = amount_reward; new_pool.rewards_pool = rewards; // // Pool Funds PoolFunds memory funds; funds.max_wallet_participation = max_wallet; funds.max_total_participation = max_total; new_pool.funds_pool = funds; // addPoolToIndexation(pool_indice, _pools[pool_indice]); return pool_indice; } function fetchLivePoolsPlus() public view returns(uint256 [] memory, uint256 [] memory, uint256 [] memory) { uint256 [] memory amount_reward = new uint256[](activePoolsIndices.length); uint256 [] memory total_pooled = new uint256[](activePoolsIndices.length); uint256 [] memory max_pooled = new uint256[](activePoolsIndices.length); for (uint i = 0; i < activePoolsIndices.length; i++) { amount_reward[i] = _pools[activePoolsIndices[i]].rewards_pool.base_amount_reward; total_pooled[i] = _pools[activePoolsIndices[i]].total_amount_input_pooled; max_pooled[i] = _pools[activePoolsIndices[i]].funds_pool.max_total_participation; } return (amount_reward, total_pooled, max_pooled); } function fetchLivePools() public view returns(bytes32 [] memory, bytes32 [] memory, address [] memory, address [] memory, uint256 [] memory, uint256 [] memory) { bytes32 [] memory indices = new bytes32[](activePoolsIndices.length); bytes32 [] memory names = new bytes32[](activePoolsIndices.length); address [] memory input_assets = new address[](activePoolsIndices.length); address [] memory output_assets = new address[](activePoolsIndices.length); uint256 [] memory starts = new uint256[](activePoolsIndices.length); uint256 [] memory ends = new uint256[](activePoolsIndices.length); for (uint i = 0; i < activePoolsIndices.length; i++) { indices[i] = _pools[activePoolsIndices[i]].pool_indice; names[i] = _pools[activePoolsIndices[i]].pool_name; input_assets[i] = _pools[activePoolsIndices[i]].input_asset; output_assets[i] = _pools[activePoolsIndices[i]].output_asset; starts[i] = _pools[activePoolsIndices[i]].start_date; ends[i] = _pools[activePoolsIndices[i]].end_date; } return (indices, names, input_assets, output_assets, starts, ends); } function fetchAllPools() public view returns(bytes32 [] memory, bytes32 [] memory, address [] memory, address [] memory, uint256 [] memory, uint256 [] memory) { bytes32 [] memory indices = new bytes32[](allPoolsIndices.length); bytes32 [] memory names = new bytes32[](allPoolsIndices.length); address [] memory input_assets = new address[](allPoolsIndices.length); address [] memory output_assets = new address[](allPoolsIndices.length); uint256 [] memory starts = new uint256[](allPoolsIndices.length); uint256 [] memory ends = new uint256[](allPoolsIndices.length); for (uint i = 0; i < allPoolsIndices.length; i++) { indices[i] = _pools[allPoolsIndices[i]].pool_indice; names[i] = _pools[allPoolsIndices[i]].pool_name; input_assets[i] = _pools[allPoolsIndices[i]].input_asset; output_assets[i] = _pools[allPoolsIndices[i]].output_asset; starts[i] = _pools[allPoolsIndices[i]].start_date; ends[i] = _pools[allPoolsIndices[i]].end_date; } return (indices, names, input_assets, output_assets, starts, ends); } function fetchPool(bytes32 indice) public view returns(bytes32, address, address, uint256, uint256, uint256, uint256, uint256, uint256) { PoolStructure storage pool = _pools[indice]; require ( pool.pool_indice == indice, "Invalid Pool indice" ); return (pool.pool_name, pool.input_asset, pool.output_asset, pool.rewards_pool.base_amount_reward, pool.total_amount_input_pooled, pool.funds_pool.max_total_participation, pool.funds_pool.max_wallet_participation, pool.start_date, pool.end_date); } function fetchEndedPoolsPlus() public view returns(uint256 [] memory, uint256 [] memory, uint256 [] memory) { uint256 [] memory amount_reward = new uint256[](endedPoolsIndices.length); uint256 [] memory total_pooled = new uint256[](endedPoolsIndices.length); uint256 [] memory max_pooled = new uint256[](endedPoolsIndices.length); for (uint i = 0; i < endedPoolsIndices.length; i++) { amount_reward[i] = _pools[endedPoolsIndices[i]].rewards_pool.base_amount_reward; total_pooled[i] = _pools[endedPoolsIndices[i]].total_amount_input_pooled; max_pooled[i] = _pools[endedPoolsIndices[i]].funds_pool.max_total_participation; } return (amount_reward, total_pooled, max_pooled); } function fetchEndedPools() public view returns(bytes32 [] memory, bytes32 [] memory, address [] memory, address [] memory, uint256 [] memory, uint256 [] memory) { bytes32 [] memory indices = new bytes32[](endedPoolsIndices.length); bytes32 [] memory names = new bytes32[](endedPoolsIndices.length); address [] memory input_assets = new address[](endedPoolsIndices.length); address [] memory output_assets = new address[](endedPoolsIndices.length); uint256 [] memory starts = new uint256[](endedPoolsIndices.length); uint256 [] memory ends = new uint256[](endedPoolsIndices.length); for (uint i = 0; i < endedPoolsIndices.length; i++) { indices[i] = _pools[endedPoolsIndices[i]].pool_indice; names[i] = _pools[endedPoolsIndices[i]].pool_name; input_assets[i] = _pools[endedPoolsIndices[i]].input_asset; output_assets[i] = _pools[endedPoolsIndices[i]].output_asset; starts[i] = _pools[endedPoolsIndices[i]].start_date; ends[i] = _pools[endedPoolsIndices[i]].end_date; } return (indices, names, input_assets, output_assets, starts, ends); } }
emit event received reward
function calculateAndSendReward(bytes32 indice, address from, uint256 inputAmount) private returns(uint256) { PoolStructure storage pool = _pools[indice]; uint256 weightPercent = inputAmount.mul(100).div(pool.funds_pool.max_wallet_participation).mul(10); uint256 rewardAmount = pool.rewards_pool.base_amount_reward * weightPercent / 10000; IERC20 output_token = IERC20(address(pool.output_asset)); require( output_token.balanceOf(address(this)) >= rewardAmount, "Invalid pool contract output funds" ); require( output_token.transfer(from, rewardAmount) == true, "Error transfer reward on the contract" ); pool.rewards_pool.amount_reward -= rewardAmount; emit RewardReceivedFromPool(pool.pool_indice, rewardAmount, from, pool.output_asset); return rewardAmount; }
13,091,705
[ 1, 18356, 871, 5079, 19890, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 4604, 1876, 3826, 17631, 1060, 12, 3890, 1578, 1547, 1812, 16, 1758, 628, 16, 2254, 5034, 810, 6275, 13, 3238, 1135, 12, 11890, 5034, 13, 288, 203, 3639, 8828, 6999, 2502, 2845, 273, 389, 27663, 63, 728, 1812, 15533, 203, 3639, 2254, 5034, 3119, 8410, 273, 810, 6275, 18, 16411, 12, 6625, 2934, 2892, 12, 6011, 18, 74, 19156, 67, 6011, 18, 1896, 67, 19177, 67, 2680, 24629, 367, 2934, 16411, 12, 2163, 1769, 203, 3639, 2254, 5034, 19890, 6275, 273, 2845, 18, 266, 6397, 67, 6011, 18, 1969, 67, 8949, 67, 266, 2913, 380, 3119, 8410, 342, 12619, 31, 203, 203, 3639, 467, 654, 39, 3462, 876, 67, 2316, 273, 467, 654, 39, 3462, 12, 2867, 12, 6011, 18, 2844, 67, 9406, 10019, 203, 3639, 2583, 12, 203, 5411, 876, 67, 2316, 18, 12296, 951, 12, 2867, 12, 2211, 3719, 1545, 19890, 6275, 16, 203, 5411, 315, 1941, 2845, 6835, 876, 284, 19156, 6, 203, 3639, 11272, 203, 540, 203, 3639, 2583, 12, 203, 2398, 876, 67, 2316, 18, 13866, 12, 2080, 16, 19890, 6275, 13, 422, 638, 16, 203, 5411, 315, 668, 7412, 19890, 603, 326, 6835, 6, 203, 3639, 11272, 203, 203, 3639, 2845, 18, 266, 6397, 67, 6011, 18, 8949, 67, 266, 2913, 3947, 19890, 6275, 31, 203, 203, 3639, 3626, 534, 359, 1060, 8872, 1265, 2864, 12, 6011, 18, 6011, 67, 728, 1812, 16, 203, 540, 19890, 6275, 16, 628, 16, 2845, 18, 2844, 67, 9406, 1769, 203, 203, 3639, 327, 19890, 6275, 31, 203, 565, 289, 2 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.7.4; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "./abstract/AbstractLeveragePortfolio.sol"; import "./interfaces/IReinsurancePool.sol"; import "./interfaces/IBMIStaking.sol"; contract ReinsurancePool is AbstractLeveragePortfolio, IReinsurancePool, OwnableUpgradeable { using SafeERC20 for ERC20; IERC20 public bmiToken; ERC20 public stblToken; IBMIStaking public bmiStaking; address public claimVotingAddress; uint256 public stblDecimals; address public aaveProtocol; address public compoundProtocol; address public yearnProtocol; event Recovered(address tokenAddress, uint256 tokenAmount); event STBLWithdrawn(address user, uint256 amount); event DefiInterestAdded(uint256 interestAmount); modifier onlyClaimVoting() { require(claimVotingAddress == _msgSender(), "RP: Caller is not a ClaimVoting contract"); _; } modifier onlyDefiProtocols() { require( aaveProtocol == _msgSender() || compoundProtocol == _msgSender() || yearnProtocol == _msgSender(), "RP: Caller is not a defi protocols contract" ); _; } function __ReinsurancePool_init() external initializer { __LeveragePortfolio_init(); __Ownable_init(); } function setDependencies(IContractsRegistry _contractsRegistry) external override onlyInjectorOrZero { stblToken = ERC20(_contractsRegistry.getUSDTContract()); bmiStaking = IBMIStaking(_contractsRegistry.getBMIStakingContract()); bmiToken = IERC20(_contractsRegistry.getBMIContract()); capitalPool = ICapitalPool(_contractsRegistry.getCapitalPoolContract()); claimVotingAddress = _contractsRegistry.getClaimVotingContract(); policyBookRegistry = IPolicyBookRegistry( _contractsRegistry.getPolicyBookRegistryContract() ); compoundProtocol = _contractsRegistry.getCompoundProtocolContract(); aaveProtocol = _contractsRegistry.getAaveProtocolContract(); yearnProtocol = _contractsRegistry.getYearnProtocolContract(); leveragePortfolioView = ILeveragePortfolioView( _contractsRegistry.getLeveragePortfolioViewContract() ); policyBookAdmin = _contractsRegistry.getPolicyBookAdminContract(); stblDecimals = stblToken.decimals(); // _transferOwnership("0xc97773e1df2cc54e51a005dff7cbbb6480ae2767"); } function withdrawBMITo(address to, uint256 amount) external override onlyClaimVoting { bmiToken.transfer(to, amount); } function withdrawSTBLTo(address to, uint256 amount) external override onlyClaimVoting { stblToken.safeTransfer(to, DecimalsConverter.convertFrom18(amount, stblDecimals)); emit STBLWithdrawn(to, amount); } function recoverERC20(address tokenAddress, uint256 tokenAmount) external { //fixing bugs of storage break , owner address is gone require(_msgSender() == address(0xc97773E1Df2cC54e51a005DFF7cBBb6480aE2767),"RP: Not an owner"); IERC20(tokenAddress).transfer(owner(), tokenAmount); emit Recovered(tokenAddress, tokenAmount); } /// @notice add the 20% of premium + portion of 80% of premium where reisnurance pool participate in coverage pools (vStable) /// @dev access CapitalPool /// @param premiumAmount uint256 the premium amount which is 20% of premium + portion of 80% function addPolicyPremium(uint256, uint256 premiumAmount) external override onlyCapitalPool { totalLiquidity += premiumAmount; emit PremiumAdded(premiumAmount); } /// @notice add the interest amount from defi protocol : access defi protocols /// @param interestAmount uint256 the interest amount from defi protocols function addInterestFromDefiProtocols(uint256 interestAmount) external override onlyDefiProtocols { uint256 amount = DecimalsConverter.convertTo18(interestAmount, stblDecimals); totalLiquidity += amount; capitalPool.addReinsurancePoolHardSTBL(interestAmount); _reevaluateProvidedLeverageStable(LeveragePortfolio.REINSURANCEPOOL, amount); emit DefiInterestAdded(amount); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256` * (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev 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); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "../../GSN/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity >=0.4.24 <0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function _isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; // solhint-disable-next-line no-inline-assembly assembly { cs := extcodesize(self) } return cs == 0; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../GSN/ContextUpgradeable.sol"; import "../proxy/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../proxy/Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.4; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; /// @notice the intention of this library is to be able to easily convert /// one amount of tokens with N decimal places /// to another amount with M decimal places library DecimalsConverter { using SafeMath for uint256; function convert( uint256 amount, uint256 baseDecimals, uint256 destinationDecimals ) internal pure returns (uint256) { if (baseDecimals > destinationDecimals) { amount = amount.div(10**(baseDecimals - destinationDecimals)); } else if (baseDecimals < destinationDecimals) { amount = amount.mul(10**(destinationDecimals - baseDecimals)); } return amount; } function convertTo18(uint256 amount, uint256 baseDecimals) internal pure returns (uint256) { return convert(amount, baseDecimals, 18); } function convertFrom18(uint256 amount, uint256 destinationDecimals) internal pure returns (uint256) { return convert(amount, 18, destinationDecimals); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.4; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; interface ISTKBMIToken is IERC20Upgradeable { function mint(address account, uint256 amount) external; function burn(address account, uint256 amount) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.4; pragma experimental ABIEncoderV2; import "./IPolicyBookFabric.sol"; import "./IClaimingRegistry.sol"; import "./IPolicyBookFacade.sol"; interface IUserLeveragePool { enum WithdrawalStatus {NONE, PENDING, READY, EXPIRED} struct WithdrawalInfo { uint256 withdrawalAmount; uint256 readyToWithdrawDate; bool withdrawalAllowed; } struct BMIMultiplierFactors { uint256 poolMultiplier; uint256 leverageProvided; uint256 multiplier; } /// @notice Returns type of contract this PolicyBook covers, access: ANY /// @return _type is type of contract function contractType() external view returns (IPolicyBookFabric.ContractType _type); function userLiquidity(address account) external view returns (uint256); function a2_ProtocolConstant() external view returns (uint256); function EPOCH_DURATION() external view returns (uint256); function READY_TO_WITHDRAW_PERIOD() external view returns (uint256); function epochStartTime() external view returns (uint256); function withdrawalsInfo(address _userAddr) external view returns ( uint256 _withdrawalAmount, uint256 _readyToWithdrawDate, bool _withdrawalAllowed ); function __UserLeveragePool_init( IPolicyBookFabric.ContractType _contractType, string calldata _description, string calldata _projectSymbol ) external; function getEpoch(uint256 time) external view returns (uint256); /// @notice get STBL equivalent function convertBMIXToSTBL(uint256 _amount) external view returns (uint256); /// @notice get BMIX equivalent function convertSTBLToBMIX(uint256 _amount) external view returns (uint256); /// @notice forces an update of RewardsGenerator multiplier function forceUpdateBMICoverStakingRewardMultiplier() external; /// @notice function to get precise current cover and liquidity function getNewCoverAndLiquidity() external view returns (uint256 newTotalCoverTokens, uint256 newTotalLiquidity); function updateEpochsInfo() external; function secondsToEndCurrentEpoch() external view returns (uint256); /// @notice Let user to add liquidity by supplying stable coin, access: ANY /// @param _liqudityAmount is amount of stable coin tokens to secure function addLiquidity(uint256 _liqudityAmount) external; // /// @notice Let eligible contracts add liqiudity for another user by supplying stable coin // /// @param _liquidityHolderAddr is address of address to assign cover // /// @param _liqudityAmount is amount of stable coin tokens to secure // function addLiquidityFor(address _liquidityHolderAddr, uint256 _liqudityAmount) external; function addLiquidityAndStake(uint256 _liquidityAmount, uint256 _stakeSTBLAmount) external; function getAvailableBMIXWithdrawableAmount(address _userAddr) external view returns (uint256); function getWithdrawalStatus(address _userAddr) external view returns (WithdrawalStatus); function requestWithdrawal(uint256 _tokensToWithdraw) external; // function requestWithdrawalWithPermit( // uint256 _tokensToWithdraw, // uint8 _v, // bytes32 _r, // bytes32 _s // ) external; function unlockTokens() external; /// @notice Let user to withdraw deposited liqiudity, access: ANY function withdrawLiquidity() external; ///@notice for doing defi hard rebalancing, access: CapitalPool function updateLiquidity(uint256 _newLiquidity) external; function getAPY() external view returns (uint256); function whitelisted() external view returns (bool); function whitelist(bool _whitelisted) external; /// @notice set max total liquidity for the pool /// @param _maxCapacities uint256 the max total liquidity function setMaxCapacities(uint256 _maxCapacities) external; function setA2_ProtocolConstant(uint256 _a2_ProtocolConstant) external; /// @notice Getting number stats, access: ANY /// @return _maxCapacities is a max liquidity of the pool /// @return _totalSTBLLiquidity is PolicyBook's liquidity /// @return _totalLeveragedLiquidity is becuase to follow the same function in policy book /// @return _stakedSTBL is how much stable coin are staked on this PolicyBook /// @return _annualProfitYields is its APY /// @return _annualInsuranceCost is becuase to follow the same function in policy book /// @return _bmiXRatio is multiplied by 10**18. To get STBL representation function numberStats() external view returns ( uint256 _maxCapacities, uint256 _totalSTBLLiquidity, uint256 _totalLeveragedLiquidity, uint256 _stakedSTBL, uint256 _annualProfitYields, uint256 _annualInsuranceCost, uint256 _bmiXRatio ); /// @notice Getting info, access: ANY /// @return _symbol is the symbol of PolicyBook (bmiXCover) /// @return _insuredContract is an addres of insured contract /// @return _contractType is becuase to follow the same function in policy book /// @return _whitelisted is a state of whitelisting function info() external view returns ( string memory _symbol, address _insuredContract, IPolicyBookFabric.ContractType _contractType, bool _whitelisted ); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.4; pragma experimental ABIEncoderV2; interface IReinsurancePool { function withdrawBMITo(address to, uint256 amount) external; function withdrawSTBLTo(address to, uint256 amount) external; /// @notice add the interest amount from defi protocol : access defi protocols /// @param intrestAmount uint256 the interest amount from defi protocols function addInterestFromDefiProtocols(uint256 intrestAmount) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.4; pragma experimental ABIEncoderV2; import "./IPolicyBookFabric.sol"; interface IPolicyBookRegistry { struct PolicyBookStats { string symbol; address insuredContract; IPolicyBookFabric.ContractType contractType; uint256 maxCapacity; uint256 totalSTBLLiquidity; uint256 totalLeveragedLiquidity; uint256 stakedSTBL; uint256 APY; uint256 annualInsuranceCost; uint256 bmiXRatio; bool whitelisted; } function policyBooksByInsuredAddress(address insuredContract) external view returns (address); function policyBookFacades(address facadeAddress) external view returns (address); /// @notice Adds PolicyBook to registry, access: PolicyFabric function add( address insuredContract, IPolicyBookFabric.ContractType contractType, address policyBook, address facadeAddress ) external; function whitelist(address policyBookAddress, bool whitelisted) external; /// @notice returns required allowances for the policybooks function getPoliciesPrices( address[] calldata policyBooks, uint256[] calldata epochsNumbers, uint256[] calldata coversTokens ) external view returns (uint256[] memory _durations, uint256[] memory _allowances); /// @notice Buys a batch of policies function buyPolicyBatch( address[] calldata policyBooks, uint256[] calldata epochsNumbers, uint256[] calldata coversTokens ) external; /// @notice Checks if provided address is a PolicyBook function isPolicyBook(address policyBook) external view returns (bool); /// @notice Checks if provided address is a policyBookFacade function isPolicyBookFacade(address _facadeAddress) external view returns (bool); /// @notice Checks if provided address is a user leverage pool function isUserLeveragePool(address policyBookAddress) external view returns (bool); /// @notice Returns number of registered PolicyBooks with certain contract type function countByType(IPolicyBookFabric.ContractType contractType) external view returns (uint256); /// @notice Returns number of registered PolicyBooks, access: ANY function count() external view returns (uint256); function countByTypeWhitelisted(IPolicyBookFabric.ContractType contractType) external view returns (uint256); function countWhitelisted() external view returns (uint256); /// @notice Listing registered PolicyBooks with certain contract type, access: ANY /// @return _policyBooksArr is array of registered PolicyBook addresses with certain contract type function listByType( IPolicyBookFabric.ContractType contractType, uint256 offset, uint256 limit ) external view returns (address[] memory _policyBooksArr); /// @notice Listing registered PolicyBooks, access: ANY /// @return _policyBooksArr is array of registered PolicyBook addresses function list(uint256 offset, uint256 limit) external view returns (address[] memory _policyBooksArr); function listByTypeWhitelisted( IPolicyBookFabric.ContractType contractType, uint256 offset, uint256 limit ) external view returns (address[] memory _policyBooksArr); function listWhitelisted(uint256 offset, uint256 limit) external view returns (address[] memory _policyBooksArr); /// @notice Listing registered PolicyBooks with stats and certain contract type, access: ANY function listWithStatsByType( IPolicyBookFabric.ContractType contractType, uint256 offset, uint256 limit ) external view returns (address[] memory _policyBooksArr, PolicyBookStats[] memory _stats); /// @notice Listing registered PolicyBooks with stats, access: ANY function listWithStats(uint256 offset, uint256 limit) external view returns (address[] memory _policyBooksArr, PolicyBookStats[] memory _stats); function listWithStatsByTypeWhitelisted( IPolicyBookFabric.ContractType contractType, uint256 offset, uint256 limit ) external view returns (address[] memory _policyBooksArr, PolicyBookStats[] memory _stats); function listWithStatsWhitelisted(uint256 offset, uint256 limit) external view returns (address[] memory _policyBooksArr, PolicyBookStats[] memory _stats); /// @notice Getting stats from policy books, access: ANY /// @param policyBooks is list of PolicyBooks addresses function stats(address[] calldata policyBooks) external view returns (PolicyBookStats[] memory _stats); /// @notice Return existing Policy Book contract, access: ANY /// @param insuredContract is contract address to lookup for created IPolicyBook function policyBookFor(address insuredContract) external view returns (address); /// @notice Getting stats from policy books, access: ANY /// @param insuredContracts is list of insuredContracts in registry function statsByInsuredContracts(address[] calldata insuredContracts) external view returns (PolicyBookStats[] memory _stats); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.4; import "./IPolicyBook.sol"; import "./ILeveragePortfolio.sol"; interface IPolicyBookFacade { /// @notice Let user to buy policy by supplying stable coin, access: ANY /// @param _epochsNumber period policy will cover /// @param _coverTokens amount paid for the coverage function buyPolicy(uint256 _epochsNumber, uint256 _coverTokens) external; /// @param _holder who owns coverage /// @param _epochsNumber period policy will cover /// @param _coverTokens amount paid for the coverage function buyPolicyFor( address _holder, uint256 _epochsNumber, uint256 _coverTokens ) external; function policyBook() external view returns (IPolicyBook); function userLiquidity(address account) external view returns (uint256); /// @notice virtual funds deployed by reinsurance pool function VUreinsurnacePool() external view returns (uint256); /// @notice leverage funds deployed by reinsurance pool function LUreinsurnacePool() external view returns (uint256); /// @notice leverage funds deployed by user leverage pool function LUuserLeveragePool(address userLeveragePool) external view returns (uint256); /// @notice total leverage funds deployed to the pool sum of (VUreinsurnacePool,LUreinsurnacePool,LUuserLeveragePool) function totalLeveragedLiquidity() external view returns (uint256); function userleveragedMPL() external view returns (uint256); function reinsurancePoolMPL() external view returns (uint256); function rebalancingThreshold() external view returns (uint256); function safePricingModel() external view returns (bool); /// @notice policyBookFacade initializer /// @param pbProxy polciybook address upgreadable cotnract. function __PolicyBookFacade_init( address pbProxy, address liquidityProvider, uint256 initialDeposit ) external; /// @param _epochsNumber period policy will cover /// @param _coverTokens amount paid for the coverage /// @param _distributor if it was sold buy a whitelisted distributor, it is distributor address to receive fee (commission) function buyPolicyFromDistributor( uint256 _epochsNumber, uint256 _coverTokens, address _distributor ) external; /// @param _buyer who is buying the coverage /// @param _epochsNumber period policy will cover /// @param _coverTokens amount paid for the coverage /// @param _distributor if it was sold buy a whitelisted distributor, it is distributor address to receive fee (commission) function buyPolicyFromDistributorFor( address _buyer, uint256 _epochsNumber, uint256 _coverTokens, address _distributor ) external; /// @notice Let user to add liquidity by supplying stable coin, access: ANY /// @param _liquidityAmount is amount of stable coin tokens to secure function addLiquidity(uint256 _liquidityAmount) external; /// @notice Let user to add liquidity by supplying stable coin, access: ANY /// @param _user the one taht add liquidity /// @param _liquidityAmount is amount of stable coin tokens to secure function addLiquidityFromDistributorFor(address _user, uint256 _liquidityAmount) external; /// @notice Let user to add liquidity by supplying stable coin and stake it, /// @dev access: ANY function addLiquidityAndStake(uint256 _liquidityAmount, uint256 _stakeSTBLAmount) external; /// @notice Let user to withdraw deposited liqiudity, access: ANY function withdrawLiquidity() external; /// @notice fetches all the pools data /// @return uint256 VUreinsurnacePool /// @return uint256 LUreinsurnacePool /// @return uint256 LUleveragePool /// @return uint256 user leverage pool address function getPoolsData() external view returns ( uint256, uint256, uint256, address ); /// @notice deploy leverage funds (RP lStable, ULP lStable) /// @param deployedAmount uint256 the deployed amount to be added or substracted from the total liquidity /// @param leveragePool whether user leverage or reinsurance leverage function deployLeverageFundsAfterRebalance( uint256 deployedAmount, ILeveragePortfolio.LeveragePortfolio leveragePool ) external; /// @notice deploy virtual funds (RP vStable) /// @param deployedAmount uint256 the deployed amount to be added to the liquidity function deployVirtualFundsAfterRebalance(uint256 deployedAmount) external; /// @notice set the MPL for the user leverage and the reinsurance leverage /// @param _userLeverageMPL uint256 value of the user leverage MPL /// @param _reinsuranceLeverageMPL uint256 value of the reinsurance leverage MPL function setMPLs(uint256 _userLeverageMPL, uint256 _reinsuranceLeverageMPL) external; /// @notice sets the rebalancing threshold value /// @param _newRebalancingThreshold uint256 rebalancing threshhold value function setRebalancingThreshold(uint256 _newRebalancingThreshold) external; /// @notice sets the rebalancing threshold value /// @param _safePricingModel bool is pricing model safe (true) or not (false) function setSafePricingModel(bool _safePricingModel) external; /// @notice returns how many BMI tokens needs to approve in order to submit a claim function getClaimApprovalAmount(address user) external view returns (uint256); /// @notice upserts a withdraw request /// @dev prevents adding a request if an already pending or ready request is open. /// @param _tokensToWithdraw uint256 amount of tokens to withdraw function requestWithdrawal(uint256 _tokensToWithdraw) external; function listUserLeveragePools(uint256 offset, uint256 limit) external view returns (address[] memory _userLeveragePools); function countUserLeveragePools() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.4; interface IPolicyBookFabric { enum ContractType {CONTRACT, STABLECOIN, SERVICE, EXCHANGE, VARIOUS} /// @notice Create new Policy Book contract, access: ANY /// @param _contract is Contract to create policy book for /// @param _contractType is Contract to create policy book for /// @param _description is bmiXCover token desription for this policy book /// @param _projectSymbol replaces x in bmiXCover token symbol /// @param _initialDeposit is an amount user deposits on creation (addLiquidity()) /// @return _policyBook is address of created contract function create( address _contract, ContractType _contractType, string calldata _description, string calldata _projectSymbol, uint256 _initialDeposit, address _shieldMiningToken ) external returns (address); function createLeveragePools( ContractType _contractType, string calldata _description, string calldata _projectSymbol ) external returns (address); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.4; pragma experimental ABIEncoderV2; import "./IPolicyBookFabric.sol"; import "./IClaimingRegistry.sol"; import "./IPolicyBookFacade.sol"; interface IPolicyBook { enum WithdrawalStatus {NONE, PENDING, READY, EXPIRED} struct PolicyHolder { uint256 coverTokens; uint256 startEpochNumber; uint256 endEpochNumber; uint256 paid; uint256 reinsurancePrice; } struct WithdrawalInfo { uint256 withdrawalAmount; uint256 readyToWithdrawDate; bool withdrawalAllowed; } struct BuyPolicyParameters { address buyer; address holder; uint256 epochsNumber; uint256 coverTokens; uint256 distributorFee; address distributor; } function policyHolders(address _holder) external view returns ( uint256, uint256, uint256, uint256, uint256 ); function policyBookFacade() external view returns (IPolicyBookFacade); function setPolicyBookFacade(address _policyBookFacade) external; function EPOCH_DURATION() external view returns (uint256); function stblDecimals() external view returns (uint256); function READY_TO_WITHDRAW_PERIOD() external view returns (uint256); function whitelisted() external view returns (bool); function epochStartTime() external view returns (uint256); // @TODO: should we let DAO to change contract address? /// @notice Returns address of contract this PolicyBook covers, access: ANY /// @return _contract is address of covered contract function insuranceContractAddress() external view returns (address _contract); /// @notice Returns type of contract this PolicyBook covers, access: ANY /// @return _type is type of contract function contractType() external view returns (IPolicyBookFabric.ContractType _type); function totalLiquidity() external view returns (uint256); function totalCoverTokens() external view returns (uint256); // /// @notice return MPL for user leverage pool // function userleveragedMPL() external view returns (uint256); // /// @notice return MPL for reinsurance pool // function reinsurancePoolMPL() external view returns (uint256); // function bmiRewardMultiplier() external view returns (uint256); function withdrawalsInfo(address _userAddr) external view returns ( uint256 _withdrawalAmount, uint256 _readyToWithdrawDate, bool _withdrawalAllowed ); function __PolicyBook_init( address _insuranceContract, IPolicyBookFabric.ContractType _contractType, string calldata _description, string calldata _projectSymbol ) external; function whitelist(bool _whitelisted) external; function getEpoch(uint256 time) external view returns (uint256); /// @notice get STBL equivalent function convertBMIXToSTBL(uint256 _amount) external view returns (uint256); /// @notice get BMIX equivalent function convertSTBLToBMIX(uint256 _amount) external view returns (uint256); /// @notice submits new claim of the policy book function submitClaimAndInitializeVoting(string calldata evidenceURI) external; /// @notice submits new appeal claim of the policy book function submitAppealAndInitializeVoting(string calldata evidenceURI) external; /// @notice updates info on claim acceptance function commitClaim( address claimer, uint256 claimAmount, uint256 claimEndTime, IClaimingRegistry.ClaimStatus status ) external; /// @notice forces an update of RewardsGenerator multiplier function forceUpdateBMICoverStakingRewardMultiplier() external; /// @notice function to get precise current cover and liquidity function getNewCoverAndLiquidity() external view returns (uint256 newTotalCoverTokens, uint256 newTotalLiquidity); /// @notice view function to get precise policy price /// @param _epochsNumber is number of epochs to cover /// @param _coverTokens is number of tokens to cover /// @param _buyer address of the user who buy the policy /// @return totalSeconds is number of seconds to cover /// @return totalPrice is the policy price which will pay by the buyer function getPolicyPrice( uint256 _epochsNumber, uint256 _coverTokens, address _buyer ) external view returns ( uint256 totalSeconds, uint256 totalPrice, uint256 pricePercentage ); /// @notice Let user to buy policy by supplying stable coin, access: ANY /// @param _buyer who is transferring funds /// @param _holder who owns coverage /// @param _epochsNumber period policy will cover /// @param _coverTokens amount paid for the coverage /// @param _distributorFee distributor fee (commission). It can't be greater than PROTOCOL_PERCENTAGE /// @param _distributor if it was sold buy a whitelisted distributor, it is distributor address to receive fee (commission) function buyPolicy( address _buyer, address _holder, uint256 _epochsNumber, uint256 _coverTokens, uint256 _distributorFee, address _distributor ) external returns (uint256, uint256); function updateEpochsInfo() external; function secondsToEndCurrentEpoch() external view returns (uint256); /// @notice Let eligible contracts add liqiudity for another user by supplying stable coin /// @param _liquidityHolderAddr is address of address to assign cover /// @param _liqudityAmount is amount of stable coin tokens to secure function addLiquidityFor(address _liquidityHolderAddr, uint256 _liqudityAmount) external; /// @notice Let user to add liquidity by supplying stable coin, access: ANY /// @param _liquidityBuyerAddr address the one that transfer funds /// @param _liquidityHolderAddr address the one that owns liquidity /// @param _liquidityAmount uint256 amount to be added on behalf the sender /// @param _stakeSTBLAmount uint256 the staked amount if add liq and stake function addLiquidity( address _liquidityBuyerAddr, address _liquidityHolderAddr, uint256 _liquidityAmount, uint256 _stakeSTBLAmount ) external returns (uint256); function getAvailableBMIXWithdrawableAmount(address _userAddr) external view returns (uint256); function getWithdrawalStatus(address _userAddr) external view returns (WithdrawalStatus); function requestWithdrawal(uint256 _tokensToWithdraw, address _user) external; // function requestWithdrawalWithPermit( // uint256 _tokensToWithdraw, // uint8 _v, // bytes32 _r, // bytes32 _s // ) external; function unlockTokens() external; /// @notice Let user to withdraw deposited liqiudity, access: ANY function withdrawLiquidity(address sender) external returns (uint256); ///@notice for doing defi hard rebalancing, access: policyBookFacade function updateLiquidity(uint256 _newLiquidity) external; function getAPY() external view returns (uint256); /// @notice Getting user stats, access: ANY function userStats(address _user) external view returns (PolicyHolder memory); /// @notice Getting number stats, access: ANY /// @return _maxCapacities is a max token amount that a user can buy /// @return _totalSTBLLiquidity is PolicyBook's liquidity /// @return _totalLeveragedLiquidity is PolicyBook's leveraged liquidity /// @return _stakedSTBL is how much stable coin are staked on this PolicyBook /// @return _annualProfitYields is its APY /// @return _annualInsuranceCost is percentage of cover tokens that is required to be paid for 1 year of insurance function numberStats() external view returns ( uint256 _maxCapacities, uint256 _totalSTBLLiquidity, uint256 _totalLeveragedLiquidity, uint256 _stakedSTBL, uint256 _annualProfitYields, uint256 _annualInsuranceCost, uint256 _bmiXRatio ); /// @notice Getting info, access: ANY /// @return _symbol is the symbol of PolicyBook (bmiXCover) /// @return _insuredContract is an addres of insured contract /// @return _contractType is a type of insured contract /// @return _whitelisted is a state of whitelisting function info() external view returns ( string memory _symbol, address _insuredContract, IPolicyBookFabric.ContractType _contractType, bool _whitelisted ); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.4; pragma experimental ABIEncoderV2; import "./ILeveragePortfolio.sol"; import "./IUserLeveragePool.sol"; interface ILeveragePortfolioView { function calcM(uint256 poolUR, address leveragePoolAddress) external view returns (uint256); function calcMaxLevFunds(ILeveragePortfolio.LevFundsFactors memory factors) external view returns (uint256); function calcBMIMultiplier(IUserLeveragePool.BMIMultiplierFactors memory factors) external view returns (uint256); function getPolicyBookFacade(address _policybookAddress) external view returns (IPolicyBookFacade _coveragePool); function calcNetMPLn( ILeveragePortfolio.LeveragePortfolio leveragePoolType, address _policyBookFacade ) external view returns (uint256 _netMPLn); function calcMaxVirtualFunds(address policyBookAddress) external returns (uint256 _amountToDeploy, uint256 _maxAmount); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.4; interface ILeveragePortfolio { enum LeveragePortfolio {USERLEVERAGEPOOL, REINSURANCEPOOL} struct LevFundsFactors { uint256 netMPL; uint256 netMPLn; address policyBookAddr; } function targetUR() external view returns (uint256); function d_ProtocolConstant() external view returns (uint256); function a_ProtocolConstant() external view returns (uint256); function max_ProtocolConstant() external view returns (uint256); /// @notice deploy lStable from user leverage pool or reinsurance pool using 2 formulas: access by policybook. /// @param leveragePoolType LeveragePortfolio is determine the pool which call the function function deployLeverageStableToCoveragePools(LeveragePortfolio leveragePoolType) external returns (uint256); /// @notice deploy the vStable from RP in v2 and for next versions it will be from RP and LP : access by policybook. function deployVirtualStableToCoveragePools() external returns (uint256); /// @notice set the threshold % for re-evaluation of the lStable provided across all Coverage pools : access by owner /// @param threshold uint256 is the reevaluatation threshold function setRebalancingThreshold(uint256 threshold) external; /// @notice set the protocol constant : access by owner /// @param _targetUR uint256 target utitlization ration /// @param _d_ProtocolConstant uint256 D protocol constant /// @param _a1_ProtocolConstant uint256 A1 protocol constant /// @param _max_ProtocolConstant uint256 the max % included function setProtocolConstant( uint256 _targetUR, uint256 _d_ProtocolConstant, uint256 _a1_ProtocolConstant, uint256 _max_ProtocolConstant ) external; /// @notice calc M factor by formual M = min( abs((1/ (Tur-UR))*d) /a, max) /// @param poolUR uint256 utitilization ratio for a coverage pool /// @return uint256 M facotr //function calcM(uint256 poolUR) external returns (uint256); /// @return uint256 the amount of vStable stored in the pool function totalLiquidity() external view returns (uint256); /// @notice add the portion of 80% of premium to user leverage pool where the leverage provide lstable : access policybook /// add the 20% of premium + portion of 80% of premium where reisnurance pool participate in coverage pools (vStable) : access policybook /// @param epochsNumber uint256 the number of epochs which the policy holder will pay a premium for /// @param premiumAmount uint256 the premium amount which is a portion of 80% of the premium function addPolicyPremium(uint256 epochsNumber, uint256 premiumAmount) external; /// @notice Used to get a list of coverage pools which get leveraged , use with count() /// @return _coveragePools a list containing policybook addresses function listleveragedCoveragePools(uint256 offset, uint256 limit) external view returns (address[] memory _coveragePools); /// @notice get count of coverage pools which get leveraged function countleveragedCoveragePools() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.4; pragma experimental ABIEncoderV2; interface IContractsRegistry { function getUniswapRouterContract() external view returns (address); function getUniswapBMIToETHPairContract() external view returns (address); function getUniswapBMIToUSDTPairContract() external view returns (address); function getSushiswapRouterContract() external view returns (address); function getSushiswapBMIToETHPairContract() external view returns (address); function getSushiswapBMIToUSDTPairContract() external view returns (address); function getSushiSwapMasterChefV2Contract() external view returns (address); function getWETHContract() external view returns (address); function getUSDTContract() external view returns (address); function getBMIContract() external view returns (address); function getPriceFeedContract() external view returns (address); function getPolicyBookRegistryContract() external view returns (address); function getPolicyBookFabricContract() external view returns (address); function getBMICoverStakingContract() external view returns (address); function getBMICoverStakingViewContract() external view returns (address); function getLegacyRewardsGeneratorContract() external view returns (address); function getRewardsGeneratorContract() external view returns (address); function getBMIUtilityNFTContract() external view returns (address); function getNFTStakingContract() external view returns (address); function getLiquidityMiningContract() external view returns (address); function getClaimingRegistryContract() external view returns (address); function getPolicyRegistryContract() external view returns (address); function getLiquidityRegistryContract() external view returns (address); function getClaimVotingContract() external view returns (address); function getReinsurancePoolContract() external view returns (address); function getLeveragePortfolioViewContract() external view returns (address); function getCapitalPoolContract() external view returns (address); function getPolicyBookAdminContract() external view returns (address); function getPolicyQuoteContract() external view returns (address); function getLegacyBMIStakingContract() external view returns (address); function getBMIStakingContract() external view returns (address); function getSTKBMIContract() external view returns (address); function getVBMIContract() external view returns (address); function getLegacyLiquidityMiningStakingContract() external view returns (address); function getLiquidityMiningStakingETHContract() external view returns (address); function getLiquidityMiningStakingUSDTContract() external view returns (address); function getReputationSystemContract() external view returns (address); function getAaveProtocolContract() external view returns (address); function getAaveLendPoolAddressProvdierContract() external view returns (address); function getAaveATokenContract() external view returns (address); function getCompoundProtocolContract() external view returns (address); function getCompoundCTokenContract() external view returns (address); function getCompoundComptrollerContract() external view returns (address); function getYearnProtocolContract() external view returns (address); function getYearnVaultContract() external view returns (address); function getYieldGeneratorContract() external view returns (address); function getShieldMiningContract() external view returns (address); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.4; pragma experimental ABIEncoderV2; import "./IPolicyBookFabric.sol"; interface IClaimingRegistry { enum ClaimStatus { CAN_CLAIM, UNCLAIMABLE, PENDING, AWAITING_CALCULATION, REJECTED_CAN_APPEAL, REJECTED, ACCEPTED } struct ClaimInfo { address claimer; address policyBookAddress; string evidenceURI; uint256 dateSubmitted; uint256 dateEnded; bool appeal; ClaimStatus status; uint256 claimAmount; } /// @notice returns anonymous voting duration function anonymousVotingDuration(uint256 index) external view returns (uint256); /// @notice returns the whole voting duration function votingDuration(uint256 index) external view returns (uint256); /// @notice returns how many time should pass before anyone could calculate a claim result function anyoneCanCalculateClaimResultAfter(uint256 index) external view returns (uint256); /// @notice returns true if a user can buy new policy of specified PolicyBook function canBuyNewPolicy(address buyer, address policyBookAddress) external view returns (bool); /// @notice submits new PolicyBook claim for the user function submitClaim( address user, address policyBookAddress, string calldata evidenceURI, uint256 cover, bool appeal ) external returns (uint256); /// @notice returns true if the claim with this index exists function claimExists(uint256 index) external view returns (bool); /// @notice returns claim submition time function claimSubmittedTime(uint256 index) external view returns (uint256); /// @notice returns claim end time or zero in case it is pending function claimEndTime(uint256 index) external view returns (uint256); /// @notice returns true if the claim is anonymously votable function isClaimAnonymouslyVotable(uint256 index) external view returns (bool); /// @notice returns true if the claim is exposably votable function isClaimExposablyVotable(uint256 index) external view returns (bool); /// @notice returns true if claim is anonymously votable or exposably votable function isClaimVotable(uint256 index) external view returns (bool); /// @notice returns true if a claim can be calculated by anyone function canClaimBeCalculatedByAnyone(uint256 index) external view returns (bool); /// @notice returns true if this claim is pending or awaiting function isClaimPending(uint256 index) external view returns (bool); /// @notice returns how many claims the holder has function countPolicyClaimerClaims(address user) external view returns (uint256); /// @notice returns how many pending claims are there function countPendingClaims() external view returns (uint256); /// @notice returns how many claims are there function countClaims() external view returns (uint256); /// @notice returns a claim index of it's claimer and an ordinal number function claimOfOwnerIndexAt(address claimer, uint256 orderIndex) external view returns (uint256); /// @notice returns pending claim index by its ordinal index function pendingClaimIndexAt(uint256 orderIndex) external view returns (uint256); /// @notice returns claim index by its ordinal index function claimIndexAt(uint256 orderIndex) external view returns (uint256); /// @notice returns current active claim index by policybook and claimer function claimIndex(address claimer, address policyBookAddress) external view returns (uint256); /// @notice returns true if the claim is appealed function isClaimAppeal(uint256 index) external view returns (bool); /// @notice returns current status of a claim function policyStatus(address claimer, address policyBookAddress) external view returns (ClaimStatus); /// @notice returns current status of a claim function claimStatus(uint256 index) external view returns (ClaimStatus); /// @notice returns the claim owner (claimer) function claimOwner(uint256 index) external view returns (address); /// @notice returns the claim PolicyBook function claimPolicyBook(uint256 index) external view returns (address); /// @notice returns claim info by its index function claimInfo(uint256 index) external view returns (ClaimInfo memory _claimInfo); function getAllPendingClaimsAmount() external view returns (uint256 _totalClaimsAmount); function getClaimableAmounts(uint256[] memory _claimIndexes) external view returns (uint256); /// @notice marks the user's claim as Accepted function acceptClaim(uint256 index) external; /// @notice marks the user's claim as Rejected function rejectClaim(uint256 index) external; /// @notice Update Image Uri in case it contains material that is ilegal /// or offensive. /// @dev Only the owner of the PolicyBookAdmin can erase/update evidenceUri. /// @param _claimIndex Claim Index that is going to be updated /// @param _newEvidenceURI New evidence uri. It can be blank. function updateImageUriOfClaim(uint256 _claimIndex, string calldata _newEvidenceURI) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.4; pragma experimental ABIEncoderV2; interface ICapitalPool { struct PremiumFactors { uint256 stblAmount; uint256 premiumDurationInDays; uint256 premiumPrice; uint256 lStblDeployedByLP; uint256 vStblDeployedByRP; uint256 vStblOfCP; uint256 premiumPerDeployment; uint256 participatedlStblDeployedByLP; address userLeveragePoolAddress; } function virtualUsdtAccumulatedBalance() external view returns (uint256); function liquidityCushionBalance() external view returns (uint256); /// @notice distributes the policybook premiums into pools (CP, ULP , RP) /// @dev distributes the balances acording to the established percentages /// @param _stblAmount amount hardSTBL ingressed into the system /// @param _epochsNumber uint256 the number of epochs which the policy holder will pay a premium for /// @param _protocolFee uint256 the amount of protocol fee earned by premium function addPolicyHoldersHardSTBL( uint256 _stblAmount, uint256 _epochsNumber, uint256 _protocolFee ) external returns (uint256); /// @notice distributes the hardSTBL from the coverage providers /// @dev emits PoolBalancedUpdated event /// @param _stblAmount amount hardSTBL ingressed into the system function addCoverageProvidersHardSTBL(uint256 _stblAmount) external; /// @notice distributes the hardSTBL from the leverage providers /// @dev emits PoolBalancedUpdated event /// @param _stblAmount amount hardSTBL ingressed into the system function addLeverageProvidersHardSTBL(uint256 _stblAmount) external; /// @notice distributes the hardSTBL from the reinsurance pool /// @dev emits PoolBalancedUpdated event /// @param _stblAmount amount hardSTBL ingressed into the system function addReinsurancePoolHardSTBL(uint256 _stblAmount) external; /// @notice rebalances pools acording to v2 specification and dao enforced policies /// @dev emits PoolBalancesUpdated function rebalanceLiquidityCushion() external; /// @notice Fullfils policybook claims by transfering the balance to claimer /// @param _claimer, address of the claimer recieving the withdraw /// @param _stblAmount uint256 amount to be withdrawn function fundClaim(address _claimer, uint256 _stblAmount) external; /// @notice Withdraws liquidity from a specific policbybook to the user /// @param _sender, address of the user beneficiary of the withdraw /// @param _stblAmount uint256 amount to be withdrawn /// @param _isLeveragePool bool wether the pool is ULP or CP(policybook) function withdrawLiquidity( address _sender, uint256 _stblAmount, bool _isLeveragePool ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.4; import "./tokens/ISTKBMIToken.sol"; interface IBMIStaking { event StakedBMI(uint256 stakedBMI, uint256 mintedStkBMI, address indexed recipient); event BMIWithdrawn(uint256 amountBMI, uint256 burnedStkBMI, address indexed recipient); event UnusedRewardPoolRevoked(address recipient, uint256 amount); event RewardPoolRevoked(address recipient, uint256 amount); struct WithdrawalInfo { uint256 coolDownTimeEnd; uint256 amountBMIRequested; } function stakeWithPermit( uint256 _amountBMI, uint8 _v, bytes32 _r, bytes32 _s ) external; function stakeFor(address _user, uint256 _amountBMI) external; function stake(uint256 _amountBMI) external; function maturityAt() external view returns (uint256); function isBMIRewardUnlocked() external view returns (bool); function whenCanWithdrawBMIReward(address _address) external view returns (uint256); function unlockTokensToWithdraw(uint256 _amountBMIUnlock) external; function withdraw() external; /// @notice Getting withdraw information /// @return _amountBMIRequested is amount of bmi tokens requested to unlock /// @return _amountStkBMI is amount of stkBMI that will burn /// @return _unlockPeriod is its timestamp when user can withdraw /// returns 0 if it didn't unlocked yet. User has 48hs to withdraw /// @return _availableFor is the end date if withdraw period has already begun /// or 0 if it is expired or didn't start function getWithdrawalInfo(address _userAddr) external view returns ( uint256 _amountBMIRequested, uint256 _amountStkBMI, uint256 _unlockPeriod, uint256 _availableFor ); function addToPool(uint256 _amount) external; function stakingReward(uint256 _amount) external view returns (uint256); function getStakedBMI(address _address) external view returns (uint256); function getAPY() external view returns (uint256); function setRewardPerBlock(uint256 _amount) external; function revokeRewardPool(uint256 _amount) external; function revokeUnusedRewardPool() external; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.4; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; import "@openzeppelin/contracts/math/Math.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/EnumerableSet.sol"; import "../libraries/DecimalsConverter.sol"; import "../interfaces/IPolicyBookRegistry.sol"; import "../interfaces/ILeveragePortfolio.sol"; import "../interfaces/IPolicyBookFabric.sol"; import "../interfaces/IPolicyBook.sol"; import "../interfaces/ICapitalPool.sol"; import "../interfaces/ILeveragePortfolioView.sol"; import "./AbstractDependant.sol"; import "../Globals.sol"; abstract contract AbstractLeveragePortfolio is ILeveragePortfolio, Initializable, AbstractDependant { using SafeMath for uint256; using Math for uint256; using EnumerableSet for EnumerableSet.AddressSet; ICapitalPool public capitalPool; IPolicyBookRegistry public policyBookRegistry; ILeveragePortfolioView public leveragePortfolioView; address public policyBookAdmin; address public reinsurancePoolAddress; uint256 public override targetUR; uint256 public override d_ProtocolConstant; uint256 public override a_ProtocolConstant; uint256 public override max_ProtocolConstant; uint256 public override totalLiquidity; uint256 public rebalancingThreshold; mapping(address => uint256) public poolsLDeployedAmount; mapping(address => uint256) public poolsVDeployedAmount; EnumerableSet.AddressSet internal leveragedCoveragePools; event LeverageStableDeployed(address policyBook, uint256 deployedAmount); event VirtualStableDeployed(address policyBook, uint256 deployedAmount); event ProvidedLeverageReevaluated(LeveragePortfolio leveragePool); event PremiumAdded(uint256 premiumAmount); modifier onlyPolicyBookFacade() { require(policyBookRegistry.isPolicyBookFacade(msg.sender), "LP: No access"); _; } modifier onlyCapitalPool() { require(msg.sender == address(capitalPool), "LP: No access"); _; } modifier onlyPolicyBookAdmin() { require(msg.sender == policyBookAdmin, "LP: Not a PBA"); _; } function __LeveragePortfolio_init() internal initializer { a_ProtocolConstant = 100 * PRECISION; d_ProtocolConstant = 5 * PRECISION; targetUR = 45 * PRECISION; max_ProtocolConstant = PERCENTAGE_100; rebalancingThreshold = DEFAULT_REBALANCING_THRESHOLD; } /// @notice deploy lStable from user leverage pool or reinsurance pool using 2 formulas: access by policybook. /// @param leveragePoolType LeveragePortfolio is determine the pool which call the function function deployLeverageStableToCoveragePools(LeveragePortfolio leveragePoolType) external override onlyPolicyBookFacade returns (uint256) { return _deployLeverageStableToCoveragePools( leveragePoolType, address((IPolicyBookFacade(msg.sender)).policyBook()) ); } /// @notice deploy the vStable from RP in v2 and for next versions it will be from RP and LP : access by policybook. /// @return the amount of vstable to deploy function deployVirtualStableToCoveragePools() external override onlyPolicyBookFacade returns (uint256) { address policyBookAddr = address((IPolicyBookFacade(msg.sender)).policyBook()); return _deployVirtualStableToCoveragePools(policyBookAddr); } /// @notice add the portion of 80% of premium to user leverage pool where the leverage provide lstable : access policybook /// add the 20% of premium + portion of 80% of premium where reisnurance pool participate in coverage pools (vStable) : access policybook /// @param epochsNumber uint256 the number of epochs which the policy holder will pay a premium for , zero for RP /// @param premiumAmount uint256 the premium amount which is a portion of 80% of the premium function addPolicyPremium(uint256 epochsNumber, uint256 premiumAmount) external virtual override; /// @notice set the threshold % for re-evaluation of the lStable provided across all Coverage pools /// @param _threshold uint256 is the reevaluatation threshold function setRebalancingThreshold(uint256 _threshold) external override onlyPolicyBookAdmin { rebalancingThreshold = _threshold; } /// @notice set the protocol constant /// @notice set the protocol constant : access by owner /// @param _targetUR uint256 target utitlization ration /// @param _d_ProtocolConstant uint256 D protocol constant /// @param _a1_ProtocolConstant uint256 A1 protocol constant /// @param _max_ProtocolConstant uint256 the max % included function setProtocolConstant( uint256 _targetUR, uint256 _d_ProtocolConstant, uint256 _a1_ProtocolConstant, uint256 _max_ProtocolConstant ) external override onlyPolicyBookAdmin { targetUR = _targetUR; d_ProtocolConstant = _d_ProtocolConstant; a_ProtocolConstant = _a1_ProtocolConstant; max_ProtocolConstant = _max_ProtocolConstant; } /// @notice Used to get a list of coverage pools which get leveraged , use with count() /// @return _coveragePools a list containing policybook addresses function listleveragedCoveragePools(uint256 offset, uint256 limit) external view override returns (address[] memory _coveragePools) { uint256 to = (offset.add(limit)).min(leveragedCoveragePools.length()).max(offset); _coveragePools = new address[](to - offset); for (uint256 i = offset; i < to; i++) { _coveragePools[i - offset] = leveragedCoveragePools.at(i); } } /// @notice get count of coverage pools which get leveraged function countleveragedCoveragePools() external view override returns (uint256) { return leveragedCoveragePools.length(); } function _deployVirtualStableToCoveragePools(address policyBookAddress) internal returns (uint256 deployedAmount) { (uint256 _amountToDeploy, uint256 _maxAmount) = leveragePortfolioView.calcMaxVirtualFunds(policyBookAddress); if (_amountToDeploy > _maxAmount) { deployedAmount = _maxAmount; } else { deployedAmount = _amountToDeploy; } if (deployedAmount > 0) { poolsVDeployedAmount[policyBookAddress] = deployedAmount; leveragedCoveragePools.add(policyBookAddress); } emit VirtualStableDeployed(policyBookAddress, deployedAmount); } /// @dev using two formulas , if formula 1 get zero then use the formula 2 /// otherwise get the min value of both /// calculate the net mpl for the other pool RP or LP function _deployLeverageStableToCoveragePools( LeveragePortfolio leveragePoolType, address policyBookAddress ) internal returns (uint256 deployedAmount) { IPolicyBookFacade _policyBookFacade = leveragePortfolioView.getPolicyBookFacade(policyBookAddress); uint256 _netMPL; uint256 _netMPLn; if (leveragePoolType == LeveragePortfolio.USERLEVERAGEPOOL) { _netMPL = totalLiquidity.mul(_policyBookFacade.userleveragedMPL()).div(PERCENTAGE_100); _netMPLn += ILeveragePortfolio(reinsurancePoolAddress) .totalLiquidity() .mul(_policyBookFacade.reinsurancePoolMPL()) .div(PERCENTAGE_100); } else { _netMPL = totalLiquidity.mul(_policyBookFacade.reinsurancePoolMPL()).div( PERCENTAGE_100 ); } _netMPLn += leveragePortfolioView.calcNetMPLn( leveragePoolType, address(_policyBookFacade) ); deployedAmount = leveragePortfolioView.calcMaxLevFunds( LevFundsFactors(_netMPL, _netMPLn, policyBookAddress) ); if (deployedAmount > 0) { if (deployedAmount >= poolsVDeployedAmount[policyBookAddress]) { deployedAmount = deployedAmount.sub(poolsVDeployedAmount[policyBookAddress]); } leveragedCoveragePools.add(policyBookAddress); } else { leveragedCoveragePools.remove(policyBookAddress); } poolsLDeployedAmount[policyBookAddress] = deployedAmount.add( poolsVDeployedAmount[policyBookAddress] ); emit LeverageStableDeployed(policyBookAddress, deployedAmount); } /// @notice reevaluate all pools provided by the leverage stable upon threshold /// @param leveragePool LeveragePortfolio is determine the pool which call the function /// @param newAmount the new amount added or subtracted from the pool function _reevaluateProvidedLeverageStable(LeveragePortfolio leveragePool, uint256 newAmount) internal { uint256 _newAmountPercentage; if (totalLiquidity > 0) { _newAmountPercentage = newAmount.mul(PERCENTAGE_100).div(totalLiquidity); } if ( (totalLiquidity > 0 && _newAmountPercentage > rebalancingThreshold) || totalLiquidity == 0 ) { if (leveragePool == LeveragePortfolio.REINSURANCEPOOL) { _rebalanceAllPools(leveragePool, false); } _rebalanceAllPools(leveragePool, true); emit ProvidedLeverageReevaluated(leveragePool); } } /// @notice rebalance all pools provided by the leverage stable or virtual stable /// @param leveragePool LeveragePortfolio is determine the pool which call the function /// @param _deployLeverage wether deploy leverage or virtual function _rebalanceAllPools(LeveragePortfolio leveragePool, bool _deployLeverage) internal { uint256 _coveragePoolCount = policyBookRegistry.count(); address[] memory _policyBooksArr = policyBookRegistry.list(0, _coveragePoolCount); for (uint256 i = 0; i < _policyBooksArr.length; i++) { if (policyBookRegistry.isUserLeveragePool(_policyBooksArr[i])) continue; IPolicyBookFacade _policyBookFacade = leveragePortfolioView.getPolicyBookFacade(_policyBooksArr[i]); uint256 deployedAmount; if (_deployLeverage) { deployedAmount = _deployLeverageStableToCoveragePools( leveragePool, _policyBooksArr[i] ); _policyBookFacade.deployLeverageFundsAfterRebalance(deployedAmount, leveragePool); } else { deployedAmount = _deployVirtualStableToCoveragePools(_policyBooksArr[i]); _policyBookFacade.deployVirtualFundsAfterRebalance(deployedAmount); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.4; import "../interfaces/IContractsRegistry.sol"; abstract contract AbstractDependant { /// @dev keccak256(AbstractDependant.setInjector(address)) - 1 bytes32 private constant _INJECTOR_SLOT = 0xd6b8f2e074594ceb05d47c27386969754b6ad0c15e5eb8f691399cd0be980e76; modifier onlyInjectorOrZero() { address _injector = injector(); require(_injector == address(0) || _injector == msg.sender, "Dependant: Not an injector"); _; } function setInjector(address _injector) external onlyInjectorOrZero { bytes32 slot = _INJECTOR_SLOT; assembly { sstore(slot, _injector) } } /// @dev has to apply onlyInjectorOrZero() modifier function setDependencies(IContractsRegistry) external virtual; function injector() public view returns (address _injector) { bytes32 slot = _INJECTOR_SLOT; assembly { _injector := sload(slot) } } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.4; pragma experimental ABIEncoderV2; uint256 constant SECONDS_IN_THE_YEAR = 365 * 24 * 60 * 60; // 365 days * 24 hours * 60 minutes * 60 seconds uint256 constant DAYS_IN_THE_YEAR = 365; uint256 constant MAX_INT = type(uint256).max; uint256 constant DECIMALS18 = 10**18; uint256 constant PRECISION = 10**25; uint256 constant PERCENTAGE_100 = 100 * PRECISION; uint256 constant BLOCKS_PER_DAY = 6450; uint256 constant BLOCKS_PER_YEAR = BLOCKS_PER_DAY * 365; uint256 constant APY_TOKENS = DECIMALS18; uint256 constant PROTOCOL_PERCENTAGE = 20 * PRECISION; uint256 constant DEFAULT_REBALANCING_THRESHOLD = 10**23; uint256 constant REBALANCE_DURATION = 1 days; uint256 constant EPOCH_DAYS_AMOUNT = 7;
@notice reevaluate all pools provided by the leverage stable upon threshold @param leveragePool LeveragePortfolio is determine the pool which call the function @param newAmount the new amount added or subtracted from the pool
function _reevaluateProvidedLeverageStable(LeveragePortfolio leveragePool, uint256 newAmount) internal { uint256 _newAmountPercentage; if (totalLiquidity > 0) { _newAmountPercentage = newAmount.mul(PERCENTAGE_100).div(totalLiquidity); } if ( (totalLiquidity > 0 && _newAmountPercentage > rebalancingThreshold) || totalLiquidity == 0 ) { if (leveragePool == LeveragePortfolio.REINSURANCEPOOL) { _rebalanceAllPools(leveragePool, false); } _rebalanceAllPools(leveragePool, true); emit ProvidedLeverageReevaluated(leveragePool); } }
9,949,520
[ 1, 992, 4531, 340, 777, 16000, 2112, 635, 326, 884, 5682, 14114, 12318, 5573, 225, 884, 5682, 2864, 3519, 5682, 17163, 353, 4199, 326, 2845, 1492, 745, 326, 445, 225, 394, 6275, 326, 394, 3844, 3096, 578, 10418, 329, 628, 326, 2845, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 992, 4531, 340, 19254, 1682, 5682, 30915, 12, 1682, 5682, 17163, 884, 5682, 2864, 16, 2254, 5034, 394, 6275, 13, 203, 3639, 2713, 203, 565, 288, 203, 3639, 2254, 5034, 389, 2704, 6275, 16397, 31, 203, 3639, 309, 261, 4963, 48, 18988, 24237, 405, 374, 13, 288, 203, 5411, 389, 2704, 6275, 16397, 273, 394, 6275, 18, 16411, 12, 3194, 19666, 2833, 67, 6625, 2934, 2892, 12, 4963, 48, 18988, 24237, 1769, 203, 3639, 289, 203, 3639, 309, 261, 203, 5411, 261, 4963, 48, 18988, 24237, 405, 374, 597, 389, 2704, 6275, 16397, 405, 283, 28867, 7614, 13, 747, 203, 5411, 2078, 48, 18988, 24237, 422, 374, 203, 3639, 262, 288, 203, 5411, 309, 261, 298, 5682, 2864, 422, 3519, 5682, 17163, 18, 862, 706, 26397, 4722, 20339, 13, 288, 203, 7734, 389, 266, 12296, 1595, 16639, 12, 298, 5682, 2864, 16, 629, 1769, 203, 5411, 289, 203, 5411, 389, 266, 12296, 1595, 16639, 12, 298, 5682, 2864, 16, 638, 1769, 203, 5411, 3626, 1186, 13548, 1682, 5682, 426, 14168, 690, 12, 298, 5682, 2864, 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 ]
./full_match/69/0x8EB5A8B9732022F20ab4d3128DDf3a50a6dAa7A2/sources/contracts/ShortCollateral.sol
* @notice Called by the OptionMarket when the owner of an option settles. @param listingId The OptionListing. @param receiver The address of the receiver. @param tradeType The TradeType. @param amount The amount to settle. @param strike The strike price of the OptionListing. @param priceAtExpiry The price of baseAsset at expiry. @param listingToShortCallEthReturned The amount of ETH to be returned./ Check board has been liquidated long call finished in the money If the listing finished in the money; = we pay out the priceAtExpiry (strike - (strike - priceAtExpiry) == priceAtExpiry) Otherwise pay back the strike... Return the full balance if owed > balance due to rounding errors user was long put and it finished in the money
function processSettle( uint listingId, address receiver, OptionMarket.TradeType tradeType, uint amount, uint strike, uint priceAtExpiry, uint listingToShortCallEthReturned ) external onlyOptionMarket { require(priceAtExpiry != 0, "board must be liquidated"); require(amount > 0, "option position is 0"); if (tradeType == OptionMarket.TradeType.SHORT_CALL) { require( baseAsset.transfer(receiver, listingToShortCallEthReturned.multiplyDecimal(amount)), "base transfer failed" ); liquidityPool.sendReservedQuote(receiver, (priceAtExpiry - strike).multiplyDecimal(amount)); uint balance = quoteAsset.balanceOf(address(this)); uint owed = amount.multiplyDecimal((strike > priceAtExpiry) ? priceAtExpiry : strike); require( quoteAsset.transfer( receiver, owed > balance ? balance : owed ), "quote transfer failed" ); liquidityPool.sendReservedQuote(receiver, (strike - priceAtExpiry).multiplyDecimal(amount)); } emit OptionsSettled(listingId, receiver, strike, priceAtExpiry, tradeType, amount); }
13,238,243
[ 1, 8185, 635, 326, 2698, 3882, 278, 1347, 326, 3410, 434, 392, 1456, 26319, 1040, 18, 225, 11591, 548, 1021, 2698, 19081, 18, 225, 5971, 1021, 1758, 434, 326, 5971, 18, 225, 18542, 559, 1021, 2197, 323, 559, 18, 225, 3844, 1021, 3844, 358, 444, 5929, 18, 225, 609, 2547, 1021, 609, 2547, 6205, 434, 326, 2698, 19081, 18, 225, 6205, 861, 14633, 1021, 6205, 434, 1026, 6672, 622, 10839, 18, 225, 11591, 774, 4897, 1477, 41, 451, 22360, 1021, 3844, 434, 512, 2455, 358, 506, 2106, 18, 19, 2073, 11094, 711, 2118, 4501, 26595, 690, 1525, 745, 6708, 316, 326, 15601, 971, 326, 11591, 6708, 316, 326, 15601, 31, 273, 732, 8843, 596, 326, 6205, 861, 14633, 261, 701, 2547, 300, 261, 701, 2547, 300, 6205, 861, 14633, 13, 422, 6205, 861, 14633, 13, 5272, 8843, 1473, 326, 609, 2547, 2777, 2000, 326, 1983, 11013, 309, 2523, 329, 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, 225, 445, 1207, 694, 5929, 12, 203, 565, 2254, 11591, 548, 16, 203, 565, 1758, 5971, 16, 203, 565, 2698, 3882, 278, 18, 22583, 559, 18542, 559, 16, 203, 565, 2254, 3844, 16, 203, 565, 2254, 609, 2547, 16, 203, 565, 2254, 6205, 861, 14633, 16, 203, 565, 2254, 11591, 774, 4897, 1477, 41, 451, 22360, 203, 225, 262, 3903, 1338, 1895, 3882, 278, 288, 203, 565, 2583, 12, 8694, 861, 14633, 480, 374, 16, 315, 3752, 1297, 506, 4501, 26595, 690, 8863, 203, 565, 2583, 12, 8949, 405, 374, 16, 315, 3482, 1754, 353, 374, 8863, 203, 203, 565, 309, 261, 20077, 559, 422, 2698, 3882, 278, 18, 22583, 559, 18, 15993, 67, 13730, 13, 288, 203, 1377, 2583, 12, 203, 3639, 1026, 6672, 18, 13866, 12, 24454, 16, 11591, 774, 4897, 1477, 41, 451, 22360, 18, 7027, 1283, 5749, 12, 8949, 13, 3631, 203, 3639, 315, 1969, 7412, 2535, 6, 203, 1377, 11272, 203, 1377, 4501, 372, 24237, 2864, 18, 4661, 10435, 10257, 12, 24454, 16, 261, 8694, 861, 14633, 300, 609, 2547, 2934, 7027, 1283, 5749, 12, 8949, 10019, 203, 1377, 2254, 11013, 273, 3862, 6672, 18, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 1377, 2254, 2523, 329, 273, 3844, 18, 7027, 1283, 5749, 12443, 701, 2547, 405, 6205, 861, 14633, 13, 692, 6205, 861, 14633, 294, 609, 2547, 1769, 203, 1377, 2583, 12, 203, 3639, 3862, 6672, 18, 13866, 12, 203, 1850, 5971, 16, 203, 1850, 2523, 329, 405, 11013, 692, 11013, 294, 2523, 329, 203, 3639, 262, 16, 2 ]
./full_match/137/0x78a486306D15E7111cca541F2f1307a1cFCaF5C4/sources/contracts/IPeronio.sol
* Type representing a PE token quantity/
type PeQuantity is uint256;
4,798,385
[ 1, 559, 5123, 279, 16628, 1147, 10457, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 723, 19622, 12035, 353, 2254, 5034, 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 ]
./full_match/56/0x78AC2966D74452e408a2E0E0E41810c8155Dcc50/sources/project_/contracts/Matrix.sol
magic trade balancing algorithm(PSN*bs)/(PSNH+((PSN*rs+PSNH*rt)/rt));
function calculateTrade( uint256 rt, uint256 rs, uint256 bs ) public pure returns (uint256) { return SafeMath.div( SafeMath.mul(PSN, bs), SafeMath.add( PSNH, SafeMath.div( SafeMath.add( SafeMath.mul(PSN, rs), SafeMath.mul(PSNH, rt) ), rt ) ) ); }
3,251,476
[ 1, 11179, 18542, 324, 16142, 4886, 12, 5857, 50, 2038, 13176, 12, 5857, 50, 44, 15, 12443, 5857, 50, 5453, 15, 5857, 50, 44, 3797, 13176, 3797, 10019, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 4604, 22583, 12, 203, 3639, 2254, 5034, 8253, 16, 203, 3639, 2254, 5034, 3597, 16, 203, 3639, 2254, 5034, 7081, 203, 565, 262, 1071, 16618, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 203, 5411, 14060, 10477, 18, 2892, 12, 203, 7734, 14060, 10477, 18, 16411, 12, 5857, 50, 16, 7081, 3631, 203, 7734, 14060, 10477, 18, 1289, 12, 203, 10792, 453, 13653, 44, 16, 203, 10792, 14060, 10477, 18, 2892, 12, 203, 13491, 14060, 10477, 18, 1289, 12, 203, 18701, 14060, 10477, 18, 16411, 12, 5857, 50, 16, 3597, 3631, 203, 18701, 14060, 10477, 18, 16411, 12, 5857, 50, 44, 16, 8253, 13, 203, 13491, 262, 16, 203, 13491, 8253, 203, 10792, 262, 203, 7734, 262, 203, 5411, 11272, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity 0.7.6; abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } interface 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); } 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; } 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); } interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } 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); } abstract contract ERC165 is IERC165 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor() internal { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require( address(this).balance >= amount, "Address: insufficient balance" ); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{value: amount}(""); require( success, "Address: unable to send value, recipient may have reverted" ); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue( target, data, value, "Address: low-level call with value failed" ); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require( address(this).balance >= value, "Address: insufficient balance for call" ); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{value: value}( data ); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall( target, data, "Address: low-level static call failed" ); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall( target, data, "Address: low-level delegate call failed" ); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) private pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping(bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require( set._values.length > index, "EnumerableSet: index out of bounds" ); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } library EnumerableMap { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Map type with // bytes32 keys and values. // The Map implementation uses private functions, and user-facing // implementations (such as Uint256ToAddressMap) are just wrappers around // the underlying Map. // This means that we can only create new EnumerableMaps for types that fit // in bytes32. struct MapEntry { bytes32 _key; bytes32 _value; } struct Map { // Storage of map keys and values MapEntry[] _entries; // Position of the entry defined by a key in the `entries` array, plus 1 // because index 0 means a key is not in the map. mapping(bytes32 => uint256) _indexes; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function _set( Map storage map, bytes32 key, bytes32 value ) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) { // Equivalent to !contains(map, key) map._entries.push(MapEntry({_key: key, _value: value})); // The entry is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value map._indexes[key] = map._entries.length; return true; } else { map._entries[keyIndex - 1]._value = value; return false; } } /** * @dev Removes a key-value pair from a map. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function _remove(Map storage map, bytes32 key) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex != 0) { // Equivalent to contains(map, key) // To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one // in the array, and then remove the last entry (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = keyIndex - 1; uint256 lastIndex = map._entries.length - 1; // When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. MapEntry storage lastEntry = map._entries[lastIndex]; // Move the last entry to the index where the entry to delete is map._entries[toDeleteIndex] = lastEntry; // Update the index for the moved entry map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved entry was stored map._entries.pop(); // Delete the index for the deleted slot delete map._indexes[key]; return true; } else { return false; } } /** * @dev Returns true if the key is in the map. O(1). */ function _contains(Map storage map, bytes32 key) private view returns (bool) { return map._indexes[key] != 0; } /** * @dev Returns the number of key-value pairs in the map. O(1). */ function _length(Map storage map) private view returns (uint256) { return map._entries.length; } /** * @dev Returns the key-value pair stored at position `index` in the map. O(1). * * Note that there are no guarantees on the ordering of entries inside the * array, and it may change when more entries are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) { require( map._entries.length > index, "EnumerableMap: index out of bounds" ); MapEntry storage entry = map._entries[index]; return (entry._key, entry._value); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. */ function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) { uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key) return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function _get(Map storage map, bytes32 key) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, "EnumerableMap: nonexistent key"); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } /** * @dev Same as {_get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {_tryGet}. */ function _get( Map storage map, bytes32 key, string memory errorMessage ) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } // UintToAddressMap struct UintToAddressMap { Map _inner; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function set( UintToAddressMap storage map, uint256 key, address value ) internal returns (bool) { return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) { return _remove(map._inner, bytes32(key)); } /** * @dev Returns true if the key is in the map. O(1). */ function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) { return _contains(map._inner, bytes32(key)); } /** * @dev Returns the number of elements in the map. O(1). */ function length(UintToAddressMap storage map) internal view returns (uint256) { return _length(map._inner); } /** * @dev Returns the element stored at position `index` in the set. O(1). * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) { (bytes32 key, bytes32 value) = _at(map._inner, index); return (uint256(key), address(uint160(uint256(value)))); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. * * _Available since v3.4._ */ function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) { (bool success, bytes32 value) = _tryGet(map._inner, bytes32(key)); return (success, address(uint160(uint256(value)))); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function get(UintToAddressMap storage map, uint256 key) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key))))); } /** * @dev Same as {get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryGet}. */ function get( UintToAddressMap storage map, uint256 key, string memory errorMessage ) internal view returns (address) { return address( uint160(uint256(_get(map._inner, bytes32(key), errorMessage))) ); } } library Strings { /** * @dev Converts a `uint256` to its ASCII `string` representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); uint256 index = digits - 1; temp = value; while (temp != 0) { buffer[index--] = bytes1(uint8(48 + (temp % 10))); temp /= 10; } return string(buffer); } } /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using SafeMath for uint256; using Address for address; using EnumerableSet for EnumerableSet.UintSet; using EnumerableMap for EnumerableMap.UintToAddressMap; using Strings for uint256; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from holder address to their (enumerable) set of owned tokens mapping(address => EnumerableSet.UintSet) private _holderTokens; // Enumerable mapping from token ids to their owners EnumerableMap.UintToAddressMap private _tokenOwners; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; // Token name string private _name; // Token symbol string private _symbol; // Optional mapping for token URIs mapping(uint256 => string) private _tokenURIs; // Base URI string private _baseURI; /* * bytes4(keccak256('balanceOf(address)')) == 0x70a08231 * bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e * bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3 * bytes4(keccak256('getApproved(uint256)')) == 0x081812fc * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde * * => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^ * 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd */ bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; /* * bytes4(keccak256('name()')) == 0x06fdde03 * bytes4(keccak256('symbol()')) == 0x95d89b41 * bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd * * => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f */ bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; /* * bytes4(keccak256('totalSupply()')) == 0x18160ddd * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59 * bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7 * * => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63 */ bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); _registerInterface(_INTERFACE_ID_ERC721_METADATA); _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require( owner != address(0), "ERC721: balance query for the zero address" ); return _holderTokens[owner].length(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { return _tokenOwners.get( tokenId, "ERC721: owner query for nonexistent token" ); } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); string memory _tokenURI = _tokenURIs[tokenId]; string memory base = baseURI(); // If there is no base URI, return the token URI. if (bytes(base).length == 0) { return _tokenURI; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(base, _tokenURI)); } // If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI. return string(abi.encodePacked(base, tokenId.toString())); } /** * @dev Returns the base URI set via {_setBaseURI}. This will be * automatically added as a prefix in {tokenURI} to each token's URI, or * to the token ID if no specific URI is set for that token ID. */ function baseURI() public view virtual returns (string memory) { return _baseURI; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { return _holderTokens[owner].at(index); } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { // _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds return _tokenOwners.length(); } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { (uint256 tokenId, ) = _tokenOwners.at(index); return tokenId; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || ERC721.isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require( _exists(tokenId), "ERC721: approved query for nonexistent token" ); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require( _isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved" ); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require( _isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved" ); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require( _checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _tokenOwners.contains(tokenId); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require( _exists(tokenId), "ERC721: operator query for nonexistent token" ); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || ERC721.isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: d* * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); // internal owner _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } _holderTokens[owner].remove(tokenId); _tokenOwners.remove(tokenId); emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require( ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own" ); // internal owner require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _holderTokens[from].remove(tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(from, to, tokenId); } /** * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require( _exists(tokenId), "ERC721Metadata: URI set of nonexistent token" ); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Internal function to set the base URI for all token IDs. It is * automatically added as a prefix to the value returned in {tokenURI}, * or to the token ID if {tokenURI} is empty. */ function _setBaseURI(string memory baseURI_) internal virtual { _baseURI = baseURI_; } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (!to.isContract()) { return true; } bytes memory returndata = to.functionCall( abi.encodeWithSelector( IERC721Receiver(to).onERC721Received.selector, _msgSender(), from, tokenId, _data ), "ERC721: transfer to non ERC721Receiver implementer" ); bytes4 retval = abi.decode(returndata, (bytes4)); return (retval == _ERC721_RECEIVED); } /** * @dev Approve `to` to operate on `tokenId` * * Emits an {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); // internal owner } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor () internal { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } library Counters { using SafeMath for uint256; struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { // The {SafeMath} overflow check can be skipped here, see the comment at the top counter._value += 1; } function decrement(Counter storage counter) internal { counter._value = counter._value.sub(1); } } contract MetaTunes is ERC721, Pausable, Ownable { using Counters for Counters.Counter; using SafeMath for uint256; Counters.Counter private _tokenIdCounter; event Mint(address indexed to, uint256 indexed tokenId); uint256 public CAP; uint256 public PRICE_ONE; uint256 public PRICE_DISCOUNT_TRIPLE; uint256 public PRICE_DISCOUNT_TEN; mapping(address => bool) whitelist; uint256 presales = 0; bool mintingStop4Ever = false; constructor( string memory _token_name, string memory _token_symbol, uint256 _CAP, uint256 _PRICE_ONE ) ERC721(_token_name, _token_symbol) { CAP = _CAP; PRICE_ONE = _PRICE_ONE; PRICE_DISCOUNT_TRIPLE = _PRICE_ONE.mul(90).div(100); //10% discount PRICE_DISCOUNT_TEN = _PRICE_ONE.mul(80).div(100); //20% discount pause(); } function addToWhitelist(address[] memory wallets, bool enabled) public onlyOwner { for (uint256 i = 0; i < wallets.length; i++) { whitelist[wallets[i]] = enabled; } } function mintWhitelist(address _to, uint256 _amount) public payable { require(whitelist[msg.sender], "Not whitlisted"); require(msg.value >= 5 * 10**16 * _amount); uint256 newCap = presales.add(_amount); require(newCap <= 100, "Mint would exceed allowed presale amount"); _mintX(_to, _amount); presales = newCap; } function pause() public onlyOwner { _pause(); } function unpause() public onlyOwner { _unpause(); } function setPrice(uint256 newPrice) public onlyOwner { PRICE_ONE = newPrice; PRICE_DISCOUNT_TRIPLE = newPrice.mul(90).div(100); PRICE_DISCOUNT_TEN = newPrice.mul(80).div(100); } function mintOne(address _to) public payable whenNotPaused { require(msg.value >= PRICE_ONE, "Wrong amount sent"); _mintX(_to, 1); } function mintThree(address _to) public payable whenNotPaused { require(msg.value >= PRICE_DISCOUNT_TRIPLE, "wrong amount sent"); _mintX(_to, 3); } function mintTen(address _to) public payable whenNotPaused { require(msg.value >= PRICE_DISCOUNT_TEN, "wrong amount sent"); _mintX(_to, 10); } function _mintX(address _to, uint256 _amount) internal { uint256 totalSupply = totalSupply(); require( (totalSupply + _amount) <= CAP, "mint would exceed the totalSupply" ); require(!mintingStop4Ever, "Minting was stopped foreva eva"); for (uint256 i = 0; i < _amount; i++) { _safeMint(_to, totalSupply + i); } } function reservedMint(address _to, uint256 _amount) public onlyOwner { _mintX(_to, _amount); } function withdraw() public onlyOwner { uint256 balance = address(this).balance; payable(msg.sender).transfer(balance); } function setBaseURI(string memory _baseURI) public onlyOwner { _setBaseURI(_baseURI); } function burnUnsold() public onlyOwner { mintingStop4Ever = true; } }
* @dev Returns true if the value is in the set. O(1)./
function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); }
11,733,582
[ 1, 1356, 638, 309, 326, 460, 353, 316, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 445, 1914, 12, 1887, 694, 2502, 444, 16, 1758, 460, 13, 203, 5411, 2713, 203, 5411, 1476, 203, 5411, 1135, 261, 6430, 13, 203, 3639, 288, 203, 5411, 327, 389, 12298, 12, 542, 6315, 7872, 16, 1731, 1578, 12, 11890, 5034, 12, 11890, 16874, 12, 1132, 3719, 10019, 203, 3639, 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 ]
pragma solidity ^0.4.13; library SafeMath { function add(uint a, uint b) internal pure returns (uint c) { c = a + b; require(c >= a); } function sub(uint a, uint b) internal pure returns (uint c) { require(b <= a); c = a - b; } function mul(uint a, uint b) internal pure returns (uint c) { c = a * b; require(a == 0 || c / a == b); } function div(uint a, uint b) internal pure returns (uint c) { require(b > 0); c = a / b; } } contract IERC20Token { function totalSupply() public constant returns (uint256 totalSupply); function balanceOf(address _owner) public constant 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 constant returns (uint256 remaining); // NOT IERC20 Token function hasSDC(address _address,uint256 _quantity) public returns (bool success); function hasSDCC(address _address,uint256 _quantity) public returns (bool success); function eliminateSDCC(address _address,uint256 _quantity) public returns (bool success); function createSDCC(address _address,uint256 _quantity) public returns (bool success); function createSDC(address _address,uint256 _init_quantity, uint256 _quantity) public returns (bool success); function stakeSDC(address _address, uint256 amount) public returns(bool); function endStake(address _address, uint256 amount) public returns(bool); function chipBalanceOf(address _address) public returns (uint256 _amount); function transferChips(address _from, address _to, uint256 _value) public returns (bool success); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } // ---------------------------------------------------------------------------- // Owned contract // ---------------------------------------------------------------------------- contract Owned { address public owner; address public newOwner; event OwnershipTransferred(address indexed _from, address indexed _to); function Owned() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address _newOwner) public onlyOwner { newOwner = _newOwner; } function acceptOwnership() public { require(msg.sender == newOwner); OwnershipTransferred(owner, newOwner); owner = newOwner; newOwner = address(0); } } contract Lockable is Owned{ uint256 public lockedUntilBlock; event ContractLocked(uint256 _untilBlock, string _reason); modifier lockAffected { require(block.number > lockedUntilBlock); _; } function lockFromSelf(uint256 _untilBlock, string _reason) internal { lockedUntilBlock = _untilBlock; ContractLocked(_untilBlock, _reason); } function lockUntil(uint256 _untilBlock, string _reason) onlyOwner { lockedUntilBlock = _untilBlock; ContractLocked(_untilBlock, _reason); } } contract Token is IERC20Token, Lockable { using SafeMath for uint256; /* Public variables of the token */ string public standard; string public name; string public symbol; uint8 public decimals; uint256 public supply; address public crowdsaleContractAddress; /* Private variables of the token */ mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowances; /* Events */ event Mint(address indexed _to, uint256 _value); function Token(){ } /* Returns total supply of issued tokens */ function totalSupply() constant returns (uint256) { return supply; } /* Returns balance of address */ function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } /* Transfers tokens from your address to other */ function transfer(address _to, uint256 _value) lockAffected returns (bool success) { require(_to != 0x0 && _to != address(this)); balances[msg.sender] = balances[msg.sender].sub(_value); // Deduct senders balance balances[_to] = balances[_to].add(_value); // Add recivers blaance Transfer(msg.sender, _to, _value); // Raise Transfer event return true; } /* Approve other address to spend tokens on your account */ function approve(address _spender, uint256 _value) lockAffected returns (bool success) { allowances[msg.sender][_spender] = _value; // Set allowance Approval(msg.sender, _spender, _value); // Raise Approval event return true; } /* A contract attempts to get the coins */ function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { require(_to != 0x0 && _to != address(this)); balances[_from] = balances[_from].sub(_value); // Deduct senders balance balances[_to] = balances[_to].add(_value); // Add recipient blaance allowances[_from][msg.sender] = allowances[_from][msg.sender].sub(_value); // Deduct allowance for this address Transfer(_from, _to, _value); // Raise Transfer event return true; } function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowances[_owner][_spender]; } function mintTokens(address _to, uint256 _amount) { require(msg.sender == crowdsaleContractAddress); supply = supply.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(0x0, _to, _amount); } function salvageTokensFromContract(address _tokenAddress, address _to, uint _amount) onlyOwner { IERC20Token(_tokenAddress).transfer(_to, _amount); } } //---------------------------------------------------------------------- // Contract function to receive approval and execute function in one call // // Borrowed from MiniMeToken // ---------------------------------------------------------------------------- contract ApproveAndCallFallBack { function receiveApproval(address from, uint256 tokens, address token, bytes data) public; } // ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and an // initial fixed supply // ---------------------------------------------------------------------------- contract SoundcoinsToken is Token { address _teamAddress; // Account 3 address _saleAddress; uint256 availableSupply = 250000000; uint256 minableSupply = 750000000; address public SoundcoinsAddress; /* Balances for ships */ uint256 public total_SDCC_supply = 0; mapping (address => uint256) balances_chips; mapping (address => uint256) holdings_SDC; uint256 holdingsSupply = 0; modifier onlyAuthorized { require(msg.sender == SoundcoinsAddress); _; } /* Initializes contract */ function SoundcoinsToken(address _crowdsaleContract) public { standard = "Soundcoins Token V1.0"; name = "Soundcoins"; symbol = "SDC"; decimals = 0; supply = 1000000000; _teamAddress = msg.sender; balances[msg.sender] = 100000000; _saleAddress = _crowdsaleContract; balances[_crowdsaleContract] = 150000000; } /********* */ /* TOOLS */ /********* */ function getAvailableSupply() public returns (uint256){ return availableSupply; } function getMinableSupply() public returns (uint256){ return minableSupply; } function getHoldingsSupply() public returns (uint256){ return holdingsSupply; } function getSDCCSupply() public returns (uint256){ return total_SDCC_supply; } function getSoundcoinsAddress() public returns (address){ return SoundcoinsAddress; } // See if Address has Enough SDC function hasSDC(address _address,uint256 _quantity) public returns (bool success){ return (balances[_address] >= _quantity); } // See if Address has Enough SDC function hasSDCC(address _address, uint256 _quantity) public returns (bool success){ return (chipBalanceOf(_address) >= _quantity); } /*SDC*/ function createSDC(address _address, uint256 _init_quantity, uint256 _quantity) onlyAuthorized public returns (bool success){ require(minableSupply >= 0); balances[_address] = balances[_address].add(_quantity); availableSupply = availableSupply.add(_quantity); holdings_SDC[_address] = holdings_SDC[_address].sub(_init_quantity); minableSupply = minableSupply.sub(_quantity.sub(_init_quantity)); holdingsSupply = holdingsSupply.sub(_init_quantity); return true; } function eliminateSDCC(address _address, uint256 _quantity) onlyAuthorized public returns (bool success){ balances_chips[_address] = balances_chips[_address].sub(_quantity); total_SDCC_supply = total_SDCC_supply.sub(_quantity); return true; } function createSDCC(address _address, uint256 _quantity) onlyAuthorized public returns (bool success){ balances_chips[_address] = balances_chips[_address].add(_quantity); total_SDCC_supply = total_SDCC_supply.add(_quantity); return true; } function chipBalanceOf(address _address) public returns (uint256 _amount) { return balances_chips[_address]; } function transferChips(address _from, address _to, uint256 _value) onlyAuthorized public returns (bool success) { require(_to != 0x0 && _to != address(msg.sender)); balances_chips[_from] = balances_chips[_from].sub(_value); // Deduct senders balance balances_chips[_to] = balances_chips[_to].add(_value); // Add recivers blaance return true; } function changeSoundcoinsContract(address _newAddress) public onlyOwner { SoundcoinsAddress = _newAddress; } function stakeSDC(address _address, uint256 amount) onlyAuthorized public returns(bool){ balances[_address] = balances[_address].sub(amount); availableSupply = availableSupply.sub(amount); holdings_SDC[_address] = holdings_SDC[_address].add(amount); holdingsSupply = holdingsSupply.add(amount); return true; } function endStake(address _address, uint256 amount) onlyAuthorized public returns(bool){ balances[_address] = balances[_address].add(amount); availableSupply = availableSupply.add(amount); holdings_SDC[_address] = holdings_SDC[_address].sub(amount); holdingsSupply = holdingsSupply.sub(amount); return true; } }
Balances for ships */
modifier onlyAuthorized { require(msg.sender == SoundcoinsAddress); _; }
12,730,375
[ 1, 38, 26488, 364, 699, 7146, 342, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 9606, 1338, 15341, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 348, 772, 71, 9896, 1887, 1769, 203, 3639, 389, 31, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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 <0.9.0; //SPDX-License-Identifier: MIT import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "./FriendrCoin.sol"; contract FriendrChain is OwnableUpgradeable { event messageSent(address sender, address receiver, uint256 messageIdx); event publicMessageSent(address sender, uint256 publicMessageIdx); event messageVoted(uint256 publicMessageIdx, bool isUpvote); event swipeMatch(address swiper, address swipee); struct Profile { string name; address _address; string image; string bio; string socialMediaProfile; uint256 created_ts; uint256 deleted_ts; } struct Message { string text; address sender; bool isPublic; uint256 created_ts; uint256 deleted_ts; // TODO: is this used? I think we need to store message idx in this struct if we want to be able to delete, so that FE has index number to send to delete API } struct PublicMessage { Message message; uint256 upvotes; uint256 downvotes; address author; string authorImg; uint256 idx; } modifier onlySenderOrOwner(address _profile) { require( _profile == _msgSender() || owner() == _msgSender(), "Caller is neither the target address nor owner nor proxy admin." ); _; } mapping(address => Profile) private _profiles; // profile for an address mapping(address => mapping(address => bool)) private _swipedAddresses; // addresses swiped on by address (value indexed by address for lookup) mapping(address => mapping(address => bool)) private _swipedRightAddresses; // addresses swiped right on by address (value indexed by address for lookup) mapping(address => mapping(uint256 => address)) private _matches; // addresses matched by address mapping(address => uint256) private _matches_count; // number of matches by address used for indexed match lookup mapping(bytes => mapping(uint256 => Message)) private _messages; // message history by address pair packed into bytes using map for lookups mapping(bytes => uint256) private _messages_count; // count of messages by message pair used for lookups in _messages mapping(uint256 => address) private _accounts; // indexed list of all accounts in the contract mapping(uint256 => PublicMessage) private _public_messages; // indexed list of public messages mapping(address => mapping(uint256 => bool)) _votes_cast_by_user; // tracking which public messages a user has already voted on FriendrCoin private friendrCoin; // note that coins are issued in wei, so we need to multiply all by (10 ** 18) uint256 private initTokenReward; uint256 private defaultApprovalAmt; string public defaultMessageText; uint256 public profileCount; uint256 public publicMessageCount; uint256 private constant oneHundredMillion = 1000 * 1000 * 1000 * (10**18); // need to multiply it into wei uint256 private constant twentyMillion = oneHundredMillion / 5; uint256 private constant eightyMillion = twentyMillion * 4; function initialize() external initializer { __Ownable_init(); // mint 20% to deployer and the rest to the contract friendrCoin = new FriendrCoin( "FriendrCOIN", "FRIEND", twentyMillion, eightyMillion, owner(), address(this) ); profileCount = 0; // Init to 0 publicMessageCount = 0; // Init to 0 initTokenReward = 100 * (10**18); defaultApprovalAmt = 10000000 * (10**18); defaultMessageText = "This is the beginning of your message history."; } /** * Public Read APIs */ // Used by FE login flow to determine if wallet user has already created a profile // If Profile object created_ts == 0, then it is a default profile (not yet created) function getUserProfile(address _profile) public view returns (Profile memory) { Profile storage profile = _profiles[_profile]; if (profile.deleted_ts != 0) { // return the 0 address which we define to be nil return _profiles[address(0)]; } return profile; } function getUnseenProfiles( address _profile, uint256 limit, uint256 offset, bool isBurner ) public view returns ( Profile[] memory, uint256, uint256 ) { require( offset < profileCount, "Cannot fetch profiles indexed beyond those that exist in system" ); uint256 profileRtnCount = 0; uint256 ownTokenBalanceTier = getTokenTier( getTokenBalanceOfUser(_profile) ); Profile[] memory profiles = new Profile[](limit); uint256 missedProfiles = 0; while (profileRtnCount < limit && offset < profileCount) { // get account at index offset address currAcct = _accounts[offset]; // skip if _profile is the same as currAct if (_profile != currAcct) { // see if currAcct was already swiped by _profile // but if caller is burner wallet then we don't need to do profile lookup bool alreadySwiped = isBurner ? false : _swipedAddresses[_profile][currAcct]; if (!alreadySwiped) { uint256 counterpartyTokenBalance = getTokenBalanceOfUser( currAcct ); if ( getTokenTier(counterpartyTokenBalance) <= ownTokenBalanceTier ) { // get profile for currAcct Profile memory profToShowInQueue = _profiles[currAcct]; // if profToShowInQueue is not deleted, then add it to rtnList if (profToShowInQueue.deleted_ts == 0) { profiles[profileRtnCount] = profToShowInQueue; profileRtnCount++; } } else { missedProfiles++; } } } offset++; } // we want to return an array of the exact correct size Profile[] memory profilesToRtn = new Profile[](profileRtnCount); for (uint256 i = 0; i < profileRtnCount; i++) { profilesToRtn[i] = profiles[i]; } return (profilesToRtn, offset, missedProfiles); } function getIsMatch(address swiper, address swipee) public view returns (bool) { return _swipedRightAddresses[swiper][swipee] && _swipedRightAddresses[swipee][swiper]; } // This endpoint serves the messages loading page to see all people with whom there were recent messages // It returns profiles to display on the page that a user can click into to see message history // As well as a new offset for pagination purposes // TODO: modify this to return most recent page of conversations function getRecentMatches( address _profile, uint256 limit, uint256 offset ) public view returns (Profile[] memory, uint256) { // Fetch a page of matches uint256 matchesCount = _matches_count[_profile]; require( offset < matchesCount, "Cannot read matches indexed beyond total number of matches for this user" ); uint256 profileRtnCount = 0; Profile[] memory profiles = new Profile[](limit); while (profileRtnCount < limit && offset < matchesCount) { address _match = _matches[_profile][offset]; Profile memory _match_profile = _profiles[_match]; if (_match_profile.deleted_ts == 0) { profiles[profileRtnCount] = _match_profile; profileRtnCount++; } offset++; } // we want to return an array of the exact correct size Profile[] memory profilesToRtn = new Profile[](profileRtnCount); for (uint256 i = 0; i < profileRtnCount; i++) { profilesToRtn[i] = profiles[i]; } return (profilesToRtn, offset); } // Called when user clicks into a conversation with a match function getRecentMessagesForMatch( address _address1, address _address2, uint256 limit, uint256 offset ) public view returns (Message[] memory, uint256) { require( _address1 != _address2, "Cannot send/receive messages to/from self." ); // Note that matchKeyPair can be address1:address2 or address2:address1 depending on order of creation // So need to try other order pair if first try returns 0 matches (all matches have at least 1 match bc of default match) bytes memory matchKeyPair = fetchMessageKeyPair(_address1, _address2); uint256 messageCount = _messages_count[matchKeyPair]; require( offset < messageCount, "Cannot read messages indexed beyond total number of messages for this pair" ); Message[] memory messages = new Message[](limit); uint256 messagesToRtnCount = 0; while (messagesToRtnCount < limit && offset < messageCount) { Message memory message = _messages[matchKeyPair][offset]; if (message.deleted_ts == 0) { messages[messagesToRtnCount] = message; messagesToRtnCount++; } offset++; } // we want to return an array of the exact correct size Message[] memory messagesToRtn = new Message[](messagesToRtnCount); for (uint256 i = 0; i < messagesToRtnCount; i++) { messagesToRtn[i] = messages[i]; } return (messagesToRtn, offset); } // Called on public message dashboard load // TODO: figure out how to sort these by vote function getPublicMessages(uint256 limit, uint256 offset) public view returns (PublicMessage[] memory, uint256) { require( offset < publicMessageCount, "Cannot read public messages indexed beyond total number of public messages that exist" ); PublicMessage[] memory messages = new PublicMessage[](limit); uint256 messagesToRtnCount = 0; while (messagesToRtnCount < limit && offset < publicMessageCount) { PublicMessage memory message = _public_messages[offset]; messages[messagesToRtnCount] = message; messagesToRtnCount++; offset++; } // we want to return an array of the exact correct size PublicMessage[] memory messagesToRtn = new PublicMessage[]( messagesToRtnCount ); for (uint256 i = 0; i < messagesToRtnCount; i++) { messagesToRtn[i] = messages[i]; } return (messagesToRtn, offset); } // Gets balance of token for given wallet function getTokenBalanceOfUser(address _profile) public view returns (uint256) { return friendrCoin.balanceOf(_profile); } // Gets wallet address of FriendrCoin function getTokenAddress() public view returns (address) { return address(friendrCoin); } /** * Public Write APIs */ function createUserProfileFlow( address _profile, string memory name, string memory _image, string memory bio, string memory _socialMediaProfile ) public { require( _profile != address(0), "Cannot create a profile at the 0 address" ); // This function adds tokens to the profile upon creation // So require that a profile cannot already exist for the given address // Use updateUserProfile method to update existing profile (it does not pay tokens) Profile storage profile = _profiles[_profile]; if (profile.deleted_ts != 0) { // calling create for a deleted profile means to re-activate it profile.deleted_ts = 0; } else { // if the profile is not deleted, then we ensure it doesn't already exist require( profile.created_ts == 0, "Cannot create a profile that already exists." ); } profile.name = name; profile._address = _profile; profile.image = _image; profile.bio = bio; profile.socialMediaProfile = _socialMediaProfile; profile.created_ts = block.timestamp; // Add profile to indexed list of accounts and increment counter _accounts[profileCount] = _profile; profileCount++; // Approve this contract to spend tokens for _profile's wallet friendrCoin.approveFor(_profile, defaultApprovalAmt); // Now send tokens from this contract's wallet to _profile's wallet // Be sure that we only transfer after setting profile.created_ts because otherwise vulnerable to reentrancy attack friendrCoin.transferFrom(address(this), _profile, initTokenReward); } function swipeLeft(address _userProfile, address _swipedProfile) public { _swipedAddresses[_userProfile][_swipedProfile] = true; } function swipeRight(address _userProfile, address _swipedProfile) public { require( friendrCoin.balanceOf(_userProfile) > 0, "User doesn't have enough tokens to swipe right" ); _swipedAddresses[_userProfile][_swipedProfile] = true; _swipedRightAddresses[_userProfile][_swipedProfile] = true; // Performance optimization is to first check if match before transferring // That way don't need to transfer and then transfer back in case of match bool isMatch = _swipedRightAddresses[_swipedProfile][_userProfile]; if (isMatch) { // get number of matches for both swiper and swipee uint256 userMatchCount = _matches_count[_userProfile]; uint256 swipedMatchCount = _matches_count[_swipedProfile]; // set swiped profile as Nth match for both swiper and swipee _matches[_userProfile][userMatchCount] = _swipedProfile; _matches[_swipedProfile][swipedMatchCount] = _userProfile; // increment match count for swiper and swipee _matches_count[_userProfile]++; _matches_count[_swipedProfile]++; // Now need to return 1 token back to _swipedProfile since they didn't match initially and were thus charged one token friendrCoin.transferFrom( address(this), _swipedProfile, 1 * (10**18) ); // Now need to init default message in messages mapping bytes memory messageMapKey = buildAddressKeyPair( _userProfile, _swipedProfile ); uint256 message_ts = block.timestamp; Message memory message = Message({ text: defaultMessageText, sender: address(this), // use contract address as sender of initial message isPublic: false, created_ts: message_ts, deleted_ts: 0 }); // set the default message to index 0 and then increment message index uint256 messages_idx = _messages_count[messageMapKey]; _messages[messageMapKey][messages_idx] = message; _messages_count[messageMapKey]++; emit swipeMatch(_userProfile, _swipedProfile); } else { friendrCoin.transferFrom(_userProfile, address(this), 1 * (10**18)); } } function sendMessage( address _sender, address _receiver, string memory _text, bool _isPublic ) public { bytes memory matchKeyPair = fetchMessageKeyPair(_sender, _receiver); uint256 messageCount = _messages_count[matchKeyPair]; // now add message to end of message history for the pair and increment counter Message memory message = Message({ text: _text, sender: _sender, isPublic: _isPublic, created_ts: block.timestamp, deleted_ts: 0 }); _messages[matchKeyPair][messageCount] = message; // emit event before incrementing messageCount index so that event points to the most recent message emit messageSent(_sender, _receiver, messageCount); _messages_count[matchKeyPair]++; // if message is public, add it to indexed mapping of public messages if (_isPublic) { PublicMessage memory publicMessage = PublicMessage({ message: message, upvotes: 0, downvotes: 0, author: _sender, authorImg: _profiles[_sender].image, idx: publicMessageCount }); _public_messages[publicMessageCount] = publicMessage; // emit event before incrementing publicMessageCount index so that event points to the most recent message emit publicMessageSent(_sender, publicMessageCount); publicMessageCount++; } } function voteOnPublicMessage(uint256 publicMessageIdx, bool isUpvote) public { require( publicMessageIdx < publicMessageCount, "Cannot vote on a message that is beyond bounds of public message list" ); PublicMessage storage message = _public_messages[publicMessageIdx]; require( _msgSender() != message.author || _msgSender() == owner(), "Cannot vote on your own message" ); require( !didAlreadyVoteOnMessage(_msgSender(), publicMessageIdx) || _msgSender() == owner(), "Can only vote on a message once." ); // Now they're voting on this message _votes_cast_by_user[_msgSender()][publicMessageIdx] = true; if (isUpvote) { message.upvotes++; friendrCoin.transferFrom( address(this), message.author, 1 * (10**18) ); } else { if (message.upvotes - message.downvotes > 0) { // Can only transfer tokens away from author of publicMessage if vote count is positive friendrCoin.transferFrom( message.author, address(this), 1 * (10**18) ); } message.downvotes++; } emit messageVoted(publicMessageIdx, isUpvote); } function editProfile( address _profile, bool editName, string memory newName, bool editImage, string memory newImage, bool editBio, string memory newBio, bool editSocialMediaProfileLink, string memory newSocialMediaProfileLink ) public { require( _profiles[_profile].created_ts > 0, "Profile is not yet created" ); if (editSocialMediaProfileLink) { _profiles[_profile].socialMediaProfile = newSocialMediaProfileLink; } if (editName) { _profiles[_profile].name = newName; } if (editImage) { _profiles[_profile].image = newImage; } if (editBio) { _profiles[_profile].bio = newBio; } } function deleteProfileImage(address _profile) public { require( _profiles[_profile].created_ts > 0, "Profile is not yet created" ); _profiles[_profile].image = ""; } function deleteProfile(address _profile) public { require( _profiles[_profile].created_ts > 0, "Profile is not yet created" ); _profiles[_profile].deleted_ts = block.timestamp; } /** * Helper methods */ function buildAddressKeyPair(address _userProfile, address _swipedProfile) private pure returns (bytes memory) { return abi.encodePacked(_userProfile, _swipedProfile); } // Helper method to determine correct ordering of address1:address2 vs address2:address1 for storing messages function fetchMessageKeyPair(address _address1, address _address2) private view returns (bytes memory) { bytes memory matchKeyPair = buildAddressKeyPair(_address1, _address2); uint256 messageCount = _messages_count[matchKeyPair]; if (messageCount == 0) { // Try other pair ordering matchKeyPair = buildAddressKeyPair(_address2, _address1); messageCount = _messages_count[matchKeyPair]; // If message count is still 0, then we have an issue require( messageCount > 0, "Profile pair doesn't have any messages, perhaps match was never initialized" ); } return matchKeyPair; } function didAlreadyVoteOnMessage(address voter, uint256 publicMessageIdx) private view returns (bool) { return _votes_cast_by_user[voter][publicMessageIdx]; } function getTokenTier(uint256 tokenCount) private pure returns (uint256) { uint256 myTier = 0; while (tokenCount != 0) { tokenCount /= 10; myTier++; } return myTier; } /** * Owner-only getters and setters */ function setInitTokenReward(uint256 _newReward) public onlyOwner { initTokenReward = _newReward; } function getInitTokenReward() public view onlyOwner returns (uint256) { return initTokenReward; } function setDefaultApprovalAmt(uint256 _newDefaultApprovalAmt) public onlyOwner { defaultApprovalAmt = _newDefaultApprovalAmt; } function getDefaultApprovalAmt() public view onlyOwner returns (uint256) { return defaultApprovalAmt; } function setDefaultMessageText(string memory _text) public onlyOwner { defaultMessageText = _text; } }
addresses matched by address
mapping(address => mapping(uint256 => address)) private _matches;
1,035,554
[ 1, 13277, 4847, 635, 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 ]
[ 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2874, 12, 2867, 516, 2874, 12, 11890, 5034, 516, 1758, 3719, 3238, 389, 8436, 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 ]
pragma ton-solidity >= 0.52.0; pragma AbiHeader time; pragma AbiHeader pubkey; pragma AbiHeader expire; //================================================================================ // import "../interfaces/ILiquidFTRoot.sol"; import "../interfaces/IOwnable.sol"; import "../contracts/LiquidFTWallet.sol"; //================================================================================ // abstract contract LiquidFTRootBase is IOwnable, ILiquidFTRoot { //======================================== // Error codes uint constant ERROR_WALLET_ADDRESS_INVALID = 301; //======================================== // Variables TvmCell static _walletCode; // string static _name; // string static _symbol; // uint8 static _decimals; // uint128 _totalSupply; // string _metadata; // //======================================== // Modifiers //======================================== // Getters function getWalletCode() external view override returns (TvmCell) { return (_walletCode); } function callWalletCode() external view responsible override reserve returns (TvmCell) { return {value: 0, flag: 128}(_walletCode); } function getWalletAddress(address ownerAddress) external view override returns (address) { (address addr, ) = _getWalletInit(ownerAddress); return (addr); } function callWalletAddress(address ownerAddress) external view responsible override reserve returns (address) { (address addr, ) = _getWalletInit(ownerAddress); return {value: 0, flag: 128}(addr); } function getInfo(bool includeMetadata) external view override returns (string name, string symbol, uint8 decimals, uint128 totalSupply, string metadata) { return (_name, _symbol, _decimals, _totalSupply, includeMetadata ? _metadata : metadata); } function callInfo(bool includeMetadata) external view responsible override reserve returns (string name, string symbol, uint8 decimals, uint128 totalSupply, string metadata) { return {value: 0, flag: 128}(_name, _symbol, _decimals, _totalSupply, includeMetadata ? _metadata : metadata); } //======================================== // function setMetadata(string metadata) external onlyOwner reserve returnChange { _metadata = metadata; } //======================================== // function _getWalletInit(address ownerAddress) private inline view returns (address, TvmCell) { TvmCell stateInit = tvm.buildStateInit({ contr: LiquidFTWallet, varInit: { _rootAddress: address(this), _ownerAddress: ownerAddress }, code: _walletCode }); return (address(tvm.hash(stateInit)), stateInit); } //======================================== // function _createWallet(address ownerAddress, address notifyOnReceiveAddress, uint128 tokensAmount, uint128 value, uint16 flag, bool emitCreateWallet) internal returns (address) { if(tokensAmount > 0) { require(senderIsOwner(), ERROR_MESSAGE_SENDER_IS_NOT_MY_OWNER); _totalSupply += tokensAmount; } (address walletAddress, TvmCell stateInit) = _getWalletInit(ownerAddress); if(emitCreateWallet) { // Event emit walletCreated(ownerAddress, walletAddress); } new LiquidFTWallet{value: value, flag: flag, bounce: false, stateInit: stateInit, wid: address(this).wid}(addressZero, msg.sender, notifyOnReceiveAddress, tokensAmount); return walletAddress; } //======================================== // No returnChange here because 0 (flag 128) TONs are sent to the new wallet // function createWallet(address ownerAddress, address notifyOnReceiveAddress, uint128 tokensAmount) external override reserve returns (address) { address walletAddress = _createWallet(ownerAddress, notifyOnReceiveAddress, tokensAmount, 0, 128, true); return(walletAddress); } function callCreateWallet(address ownerAddress, address notifyOnReceiveAddress, uint128 tokensAmount) external responsible override reserve returns (address) { address walletAddress = _createWallet(ownerAddress, notifyOnReceiveAddress, tokensAmount, msg.value / 2, 0, true); return{value: 0, flag: 128}(walletAddress); } //======================================== // function burn(uint128 amount, address senderOwnerAddress, address initiatorAddress) external override reserve returnChangeTo(initiatorAddress) { (address walletAddress, ) = _getWalletInit(senderOwnerAddress); require(walletAddress == msg.sender, ERROR_WALLET_ADDRESS_INVALID); _totalSupply -= amount; // Event emit tokensBurned(amount, senderOwnerAddress); } //======================================== // function mint(uint128 amount, address targetOwnerAddress, address notifyAddress, TvmCell body) external override onlyOwner reserve { address walletAddress = _createWallet(targetOwnerAddress, addressZero, 0, msg.value / 3, 0, false); // Event emit tokensMinted(amount, targetOwnerAddress, body); if(notifyAddress != addressZero) { iFTNotify(notifyAddress).receiveNotification{value: msg.value / 3, flag: 0}(amount, targetOwnerAddress, msg.sender, body); } // Mint adds balance to root total supply _totalSupply += amount; ILiquidFTWallet(walletAddress).receiveTransfer{value: 0, flag: 128}(amount, addressZero, _ownerAddress, notifyAddress, false, body); } //======================================== // onBounce(TvmSlice slice) external { uint32 functionId = slice.decode(uint32); if (functionId == tvm.functionId(LiquidFTWallet.receiveTransfer)) { uint128 amount = slice.decode(uint128); _totalSupply -= amount; // We know for sure that initiator in "mint" process is RTW owner; _ownerAddress.transfer(0, true, 128); } } } //================================================================================ //
======================================== Event
function _createWallet(address ownerAddress, address notifyOnReceiveAddress, uint128 tokensAmount, uint128 value, uint16 flag, bool emitCreateWallet) internal returns (address) { if(tokensAmount > 0) { require(senderIsOwner(), ERROR_MESSAGE_SENDER_IS_NOT_MY_OWNER); _totalSupply += tokensAmount; } (address walletAddress, TvmCell stateInit) = _getWalletInit(ownerAddress); if(emitCreateWallet) { emit walletCreated(ownerAddress, walletAddress); } return walletAddress; }
14,086,929
[ 1, 4428, 1432, 2587, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 2640, 16936, 12, 2867, 3410, 1887, 16, 1758, 5066, 1398, 11323, 1887, 16, 2254, 10392, 2430, 6275, 16, 2254, 10392, 460, 16, 2254, 2313, 2982, 16, 1426, 3626, 1684, 16936, 13, 2713, 1135, 261, 2867, 13, 203, 565, 288, 203, 3639, 309, 12, 7860, 6275, 405, 374, 13, 203, 3639, 288, 203, 5411, 2583, 12, 15330, 2520, 5541, 9334, 5475, 67, 8723, 67, 1090, 18556, 67, 5127, 67, 4400, 67, 22114, 67, 29602, 1769, 203, 5411, 389, 4963, 3088, 1283, 1011, 2430, 6275, 31, 203, 3639, 289, 203, 540, 203, 3639, 261, 2867, 9230, 1887, 16, 399, 3489, 4020, 919, 2570, 13, 273, 389, 588, 16936, 2570, 12, 8443, 1887, 1769, 203, 3639, 309, 12, 18356, 1684, 16936, 13, 203, 3639, 288, 203, 5411, 3626, 9230, 6119, 12, 8443, 1887, 16, 9230, 1887, 1769, 203, 3639, 289, 203, 203, 203, 3639, 327, 9230, 1887, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.13; /** * * Concept: * * Phase 1 * ======= * * Create a 2 dimensional board of 100 x 100 squares * Allow a person to purchase a single square and set its colour * * Phase 2 * ======= * Allow a person to purchase a set of squares and set its colour * **/ contract BasicBoard { struct Coordinate { uint8 x; uint8 y; } struct Owner { address owner; // owner of pixel uint price; // price of pixel string colour; // pixel colour uint32 purchasedDateTime; // approx time it was purchased Coordinate coordinate; // the purchased Coordinate } // Events event Purchased(uint fromX, uint toX, uint fromY, uint toY, string colour, address owner); /** * Maximum board width */ uint public maxWidth = 1000; /** * Maximum board height */ uint public maxHeight = 1000; /** * Block size - size of a block (10x10 pixels) */ uint public blockSize = 10; /** * The basic board - a X -> Y -> Owner */ mapping (uint => mapping (uint => Owner)) private board; /** * Who created the board */ address private boardCreator; /** * emergency kill switch, disables all future sales */ bool public stopped = false; /** * Board constructor */ function BasicBoard() public { boardCreator = msg.sender; } // Accessors function purchaseSpace (uint8 fromX, uint8 toX, uint8 fromY, uint8 toY, string colour) stopInEmergency validateWithinBoardBoundary(fromX, toX, fromY, toY) public payable returns(bool) { // TODO validate price? // TODO how allow owner to sell block? // iterate the pixel space for (uint8 ix = fromX; ix <= toX; ix++) { for (uint8 iy = fromY; iy <= toY; iy++) { buyPixel(ix, iy, colour); } } // fire purchased event Purchased(fromX, toX, fromY, toY, colour, msg.sender); return true; } function buyPixel (uint8 x, uint8 y, string colour) private isForSale(x, y) returns (uint) { // Set block to colour at location board[x][y] = Owner({ owner: msg.sender, price: msg.value, // TODO is this price per pixel of total price? colour: colour, purchasedDateTime: uint32(block.timestamp), coordinate: Coordinate({x:x, y:y}) }); } /** * Return coordinate details */ function getCoordinateDetails(uint8 x, uint8 y) public constant returns (address owner, uint price, string colour, uint32 purchasedDateTime) { Owner storage o = board[x][y]; return (o.owner, o.price, o.colour, o.purchasedDateTime); } // TODO add function to get all pixels the caller owners modifier isForSale (uint8 x, uint8 y) { // Look up the existing area block Owner storage existingOwner = board[x][y]; // validate area is available OR is owned by caller require(existingOwner.owner == 0 || existingOwner.owner == msg.sender); _; } /** * Validator - the kill switch */ function toggleContractActive() isBoardAdmin public { stopped = !stopped; } /** * Validator - fails when not the board admin i.e. the creator */ modifier isBoardAdmin { assert(msg.sender == boardCreator); _; } /** * Validator - fails when area exceeds board boundary */ modifier validateWithinBoardBoundary(uint fromX, uint toX, uint fromY, uint toY) { assert(fromX >= 0 && toX <= maxWidth - 1); assert(fromY >= 0 && toY <= maxHeight - 1); _; } // kill switch validators modifier stopInEmergency { require(!stopped); _; } modifier onlyInEmergency { if (stopped) _; } }
Look up the existing area block validate area is available OR is owned by caller
modifier isForSale (uint8 x, uint8 y) { Owner storage existingOwner = board[x][y]; require(existingOwner.owner == 0 || existingOwner.owner == msg.sender); _; }
6,442,577
[ 1, 9794, 731, 326, 2062, 5091, 1203, 1954, 5091, 353, 2319, 4869, 353, 16199, 635, 4894, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 202, 20597, 353, 1290, 30746, 261, 11890, 28, 619, 16, 2254, 28, 677, 13, 288, 203, 202, 202, 5541, 2502, 2062, 5541, 273, 11094, 63, 92, 6362, 93, 15533, 203, 203, 202, 202, 6528, 12, 11711, 5541, 18, 8443, 422, 374, 747, 2062, 5541, 18, 8443, 422, 1234, 18, 15330, 1769, 203, 202, 565, 389, 31, 203, 202, 97, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.18; import "zeppelin-solidity/contracts/math/SafeMath.sol"; import "../Upgradability/StorageConsumer.sol"; import "./OwnerRegistry.sol"; import "./Registry.sol"; /** * @title OwnableRegistry * @dev Registry of token ID's that are owned by another token from a different registry */ contract OwnableRegistry is Registry, StorageConsumer { using SafeMath for uint256; /* @dev Constructor for OwnableRegistry */ function OwnableRegistry(BaseStorage storage_) StorageConsumer(storage_) public {} /** * @dev Gets address for owner registry */ function ownerRegistry() public view returns (OwnerRegistry) { return OwnerRegistry(_storage.getAddress("ownerRegistryAddress")); } /** * @dev Gets the total amount of tokens stored by the contract * @return uint256 representing the total amount of tokens */ function totalSupply() public view returns (uint256) { return _storage.getUint("totalTokens"); } /** * @dev Gets the balance of the specified token * @param _ownerTokenId token ID to query the balance of * @return uint256 representing the amount owned by the passed token ID */ function balanceOf(uint256 _ownerTokenId) public view returns (uint256) { return _storage.getUint(keccak256("ownerBalances", _ownerTokenId)); } /** * @dev Gets the list of tokens owned by a given token ID * @param _ownerTokenId uint256 to query the tokens of * @return uint256[] representing the list of tokens owned by the passed token ID */ function tokensOf(uint256 _ownerTokenId) public view returns (uint256[]) { uint256 _ownerBalance = balanceOf(_ownerTokenId); uint256[] memory _tokens = new uint256[](_ownerBalance); for (uint256 i = 0; i < _ownerBalance; i++) { _tokens[i] = getOwnedToken(_ownerTokenId, i); } return _tokens; } /** * @dev Gets the owner id of the specified token ID * @param _tokenId uint256 ID of the token to query the owner id of * @return ownerTokenId token ID currently marked as the owner id of the given token ID */ function ownerOf(uint256 _tokenId) public view returns (uint256) { uint256 ownerTokenId = getTokenOwner(_tokenId); require(ownerTokenId != 0); return ownerTokenId; } /** * @dev Returns id of owner of entry * @param _entryId The id of the entry * @return id that owns the entry with the given id */ function ownerOfEntry(uint256 _entryId) public view returns (address) { uint256 parentEntryId = ownerOf(_entryId); return ownerRegistry().ownerOfEntry(parentEntryId); } /** * @dev Mint token function * @param _ownerTokenId uint256 ID of the token that will own the minted token * @param _tokenId uint256 ID of the token to be minted by the msg.sender */ function _mint(uint256 _ownerTokenId, uint256 _tokenId) internal { require(_ownerTokenId != 0); addToken(_ownerTokenId, _tokenId); } /** * @dev Internal function to get token owner by token ID * @param tokenId uint256 ID of the token to get the owner for * @return uint255 The ID of the token that owns the token an with ID of tokenId */ function getTokenOwner(uint256 tokenId) private view returns (uint256) { return _storage.getUint(keccak256("tokenOwners", tokenId)); } /** * @dev Internal function to get an ID value from list of owned token ID's * @param ownerTokenId The token ID for the owner of the token list * @param tokenIndex uint256 The index of the token ID value within the list * @return uint256 The token ID for the given owner and token index */ function getOwnedToken(uint256 ownerTokenId, uint256 tokenIndex) private view returns (uint256) { return _storage.getUint(keccak256("ownedTokens", ownerTokenId, tokenIndex)); } /** * @dev Internal function to get the index of a token ID within the owned tokens list * @param tokenId uint256 ID of the token to get the index for * @return uint256 The index of the token for the given ID */ function getOwnedTokenIndex(uint256 tokenId) private view returns (uint256) { return _storage.getUint(keccak256("ownedTokensIndex", tokenId)); } /** * @dev Internal function to add a token ID to the list of a given owner token ID * @param _toOwnerTokenId uint256 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 owner token ID */ function addToken(uint256 _toOwnerTokenId, uint256 _tokenId) private { require(getTokenOwner(_tokenId) == 0); setTokenOwner(_tokenId, _toOwnerTokenId); uint256 length = balanceOf(_toOwnerTokenId); pushOwnedToken(_toOwnerTokenId, _tokenId); setOwnedTokenIndex(_tokenId, length); incrementTotalTokens(); } /** * @dev Internal function to increase totalTokens by 1 */ function incrementTotalTokens() private { _storage.setUint("totalTokens", totalSupply().add(1)); } /** * @dev Internal function to decrease totalTokens by 1 */ function decrementTotalTokens() private { _storage.setUint("totalTokens", totalSupply().sub(1)); } /** * @dev Internal function to set token owner by token ID * @param tokenId uint256 ID of the token to set the owner for * @param ownerTokenId uint256 The ID of the token owner */ function setTokenOwner(uint256 tokenId, uint256 ownerTokenId) private { _storage.setUint(keccak256("tokenOwners", tokenId), ownerTokenId); } /** * @dev Internal function to increment an owner's token balance by 1 * @param ownerTokenId uint256 The owner's token ID */ function incrementOwnerBalance(uint256 ownerTokenId) private { _storage.setUint(keccak256("ownerBalances", ownerTokenId), balanceOf(ownerTokenId).add(1)); } /** * @dev Internal function to decrement an owner's token balance by 1 * @param ownerTokenId uint256 The owner's token ID */ function decrementOwnerBalance(uint256 ownerTokenId) private { _storage.setUint(keccak256("ownerBalances", ownerTokenId), balanceOf(ownerTokenId).sub(1)); } /** * @dev Internal function to set an ID value within a list of owned token ID's * @param ownerTokenId uint256 The token ID of the owner of the token list * @param tokenIndex uint256 The index to set within the owned token list * @param tokenId uint256 The ID of the token to set */ function setOwnedToken(uint256 ownerTokenId, uint256 tokenIndex, uint256 tokenId) private { _storage.setUint(keccak256("ownedTokens", ownerTokenId, tokenIndex), tokenId); } /** * @dev Internal function to append an ID value to a list of owned token ID's * @param ownerTokenId uint256 The token ID of the owner of the token list * @param tokenId uint256 The token ID to append */ function pushOwnedToken(uint256 ownerTokenId, uint256 tokenId) private { _storage.setUint(keccak256("ownedTokens", ownerTokenId, balanceOf(ownerTokenId)), tokenId); incrementOwnerBalance(ownerTokenId); } /** * @dev Internal function to set the index of a token ID within the owned tokens list * @param tokenId uint256 ID of the token to set the index for * @param tokenIndex uint256 The token index to set for the given token ID */ function setOwnedTokenIndex(uint256 tokenId, uint256 tokenIndex) private { _storage.setUint(keccak256("ownedTokensIndex", tokenId), tokenIndex); } }
* @dev Internal function to decrement an owner's token balance by 1 @param ownerTokenId uint256 The owner's token ID/
function decrementOwnerBalance(uint256 ownerTokenId) private { _storage.setUint(keccak256("ownerBalances", ownerTokenId), balanceOf(ownerTokenId).sub(1)); }
14,043,051
[ 1, 3061, 445, 358, 15267, 392, 3410, 1807, 1147, 11013, 635, 404, 225, 3410, 1345, 548, 2254, 5034, 1021, 3410, 1807, 1147, 1599, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 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, 225, 445, 15267, 5541, 13937, 12, 11890, 5034, 3410, 1345, 548, 13, 3238, 288, 203, 565, 389, 5697, 18, 542, 5487, 12, 79, 24410, 581, 5034, 2932, 8443, 38, 26488, 3113, 3410, 1345, 548, 3631, 11013, 951, 12, 8443, 1345, 548, 2934, 1717, 12, 21, 10019, 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 ]
/** * @title ClaimableCrowdsale * @title TORX.network claimable crowdsale contract. */ contract ClaimableCrowdsale is Pausable { using SafeMath for uint256; // all accepted ethers will be sent to this address address beneficiaryAddress1; address beneficiaryAddress2; address beneficiaryAddress3; // all remain tokens after ICO should go to that address address public bankAddress; // token instance TORXToken public token; uint256 public maxTokensAmount; uint256 public issuedTokensAmount = 0; uint256 public minBuyableAmount; uint256 public tokenRate; // amount of TORX per 1 ETH bool public isFinished = false; // buffer for claimable tokens mapping(address => uint256) public tokens; mapping(address => bool) public approved; mapping(uint32 => address) internal tokenReceivers; uint32 internal receiversCount; /** * Events for token purchase logging */ event TokenBought(address indexed _buyer, uint256 _tokens, uint256 _amount); event TokenAdded(address indexed _receiver, uint256 _tokens, uint256 _equivalentAmount); event TokenToppedUp(address indexed _receiver, uint256 _tokens, uint256 _equivalentAmount); event TokenSubtracted(address indexed _receiver, uint256 _tokens, uint256 _equivalentAmount); event TokenSent(address indexed _receiver, uint256 _tokens); modifier inProgress() { require (!isFinished); require (issuedTokensAmount <= maxTokensAmount); _; } /** * @param _tokenAddress address of a TORX token contract * @param _bankAddress address for remain TORX tokens accumulation * @param _beneficiaryAddress1 - 1/2 accepted ETH go to this address * @param _beneficiaryAddress1 - 1/4 accepted ETH go to this address * @param _beneficiaryAddress1 - 1/4 accepted ETH go to this address * @param _tokenRate rate TORX per 1 ETH * @param _minBuyableAmount min ETH per each buy action (in ETH wei) * @param _maxTokensAmount ICO TORX capacity (in TORX wei) * */ function ClaimableCrowdsale( address _tokenAddress, address _bankAddress, address _beneficiaryAddress1, address _beneficiaryAddress2, address _beneficiaryAddress3, uint256 _tokenRate, uint256 _minBuyableAmount, uint256 _maxTokensAmount ) { token = TORXToken(_tokenAddress); bankAddress = _bankAddress; beneficiaryAddress1 = _beneficiaryAddress1; beneficiaryAddress2 = _beneficiaryAddress2; beneficiaryAddress3 = _beneficiaryAddress3; tokenRate = _tokenRate; minBuyableAmount = _minBuyableAmount; maxTokensAmount = _maxTokensAmount; } /* * @dev Set new TORX token exchange rate. */ function setTokenRate(uint256 _tokenRate) onlyOwner { require (_tokenRate > 0); tokenRate = _tokenRate; } /** * Buy TORX. Tokens will be stored in contract until claim stage */ function buy() payable inProgress whenNotPaused { uint256 payAmount = msg.value; uint256 returnAmount = 0; uint256 Amount1 = 0; uint256 Amount2 = 0; uint256 Amount3 = 0; // calculate token amount to be transfered to investor uint256 tokensAmount = tokenRate.mul(payAmount); if (issuedTokensAmount + tokensAmount > maxTokensAmount) { tokensAmount = maxTokensAmount.sub(issuedTokensAmount); payAmount = tokensAmount.div(tokenRate); returnAmount = msg.value.sub(payAmount); } issuedTokensAmount = issuedTokensAmount.add(tokensAmount); require (issuedTokensAmount <= maxTokensAmount); storeTokens(msg.sender, tokensAmount); TokenBought(msg.sender, tokensAmount, payAmount); Amount1 = payAmount/2; Amount2 = payAmount/4; Amount3 = payAmount/4; beneficiaryAddress1.transfer(Amount1); beneficiaryAddress2.transfer(Amount2); beneficiaryAddress3.transfer(Amount3); if (returnAmount > 0) { msg.sender.transfer(returnAmount); } } /** * Add TORX payed by another crypto (BTC, LTC). Tokens will be stored in contract until claim stage */ function add(address _receiver, uint256 _equivalentEthAmount) onlyOwner inProgress whenNotPaused { uint256 tokensAmount = tokenRate.mul(_equivalentEthAmount); issuedTokensAmount = issuedTokensAmount.add(tokensAmount); storeTokens(_receiver, tokensAmount); TokenAdded(_receiver, tokensAmount, _equivalentEthAmount); } /** * Add TORX by referral program. Tokens will be stored in contract until claim stage */ function topUp(address _receiver, uint256 _equivalentEthAmount) onlyOwner whenNotPaused { uint256 tokensAmount = tokenRate.mul(_equivalentEthAmount); issuedTokensAmount = issuedTokensAmount.add(tokensAmount); storeTokens(_receiver, tokensAmount); TokenToppedUp(_receiver, tokensAmount, _equivalentEthAmount); } /** * Reduce bought TORX amount. Emergency use only */ function sub(address _receiver, uint256 _equivalentEthAmount) onlyOwner whenNotPaused { uint256 tokensAmount = tokenRate.mul(_equivalentEthAmount); require (tokens[_receiver] >= tokensAmount); tokens[_receiver] = tokens[_receiver].sub(tokensAmount); issuedTokensAmount = issuedTokensAmount.sub(tokensAmount); TokenSubtracted(_receiver, tokensAmount, _equivalentEthAmount); } /** * Internal method for storing tokens in contract until claim stage */ function storeTokens(address _receiver, uint256 _tokensAmount) internal whenNotPaused { if (tokens[_receiver] == 0) { tokenReceivers[receiversCount] = _receiver; receiversCount++; approved[_receiver] = false; } tokens[_receiver] = tokens[_receiver].add(_tokensAmount); } /** * Claim all bought TORX. Available tokens will be sent to transaction sender address if it is approved */ function claim() whenNotPaused { claimFor(msg.sender); } /** * Claim all bought TORX for specific approved address */ function claimOne(address _receiver) onlyOwner whenNotPaused { claimFor(_receiver); } /** * Claim all bought TORX for all approved addresses */ function claimAll() onlyOwner whenNotPaused { for (uint32 i = 0; i < receiversCount; i++) { address receiver = tokenReceivers[i]; if (approved[receiver] && tokens[receiver] > 0) { claimFor(receiver); } } } /** * Internal method for claiming tokens for specific approved address */ function claimFor(address _receiver) internal whenNotPaused { require(approved[_receiver]); require(tokens[_receiver] > 0); uint256 tokensToSend = tokens[_receiver]; tokens[_receiver] = 0; token.transferFrom(bankAddress, _receiver, tokensToSend); TokenSent(_receiver, tokensToSend); } function approve(address _receiver) onlyOwner whenNotPaused { approved[_receiver] = true; } /** * Finish Sale. */ function finish() onlyOwner { require (issuedTokensAmount <= maxTokensAmount); require (!isFinished); isFinished = true; token.transfer(bankAddress, token.balanceOf(this)); } function getReceiversCount() constant onlyOwner returns (uint32) { return receiversCount; } function getReceiver(uint32 i) constant onlyOwner returns (address) { return tokenReceivers[i]; } /** * Buy TORX. Tokens will be stored in contract until claim stage */ function() external payable { buy(); } } /** * @title ChangeableRateCrowdsale * @dev TORX.Network Main Sale stage */ contract ChangeableRateCrowdsale is ClaimableCrowdsale { struct RateBoundary { uint256 amount; uint256 rate; } mapping (uint => RateBoundary) public rateBoundaries; uint public currentBoundary = 0; uint public numOfBoundaries = 0; uint256 public nextBoundaryAmount; /** * @param _tokenAddress address of a TORX token contract * @param _bankAddress address for remain TORX tokens accumulation * @param _beneficiaryAddress1 - 1/2 accepted ETH go to this address * @param _beneficiaryAddress2 - 1/4 accepted ETH go to this address * @param _beneficiaryAddress3 - 1/4 accepted ETH go to this address * @param _tokenRate rate TORX per 1 ETH * @param _minBuyableAmount min ETH per each buy action (in ETH wei) * @param _maxTokensAmount ICO TORX capacity (in TORX wei) */ function ChangeableRateCrowdsale( address _tokenAddress, address _bankAddress, address _beneficiaryAddress1, address _beneficiaryAddress2, address _beneficiaryAddress3, uint256 _tokenRate, uint256 _minBuyableAmount, uint256 _maxTokensAmount ) ClaimableCrowdsale( _tokenAddress, _bankAddress, _beneficiaryAddress1, _beneficiaryAddress2, _beneficiaryAddress3, _tokenRate, _minBuyableAmount, _maxTokensAmount ) { rateBoundaries[numOfBoundaries++] = RateBoundary({ amount : 12090 ether, rate : 1450 }); rateBoundaries[numOfBoundaries++] = RateBoundary({ amount : 20590 ether, rate : 1350 }); rateBoundaries[numOfBoundaries++] = RateBoundary({ amount : 21780 ether, rate : 1200 }); rateBoundaries[numOfBoundaries++] = RateBoundary({ amount : 229070 ether, rate : 1190 }); rateBoundaries[numOfBoundaries++] = RateBoundary({ amount : 24160 ether, rate : 1180 }); rateBoundaries[numOfBoundaries++] = RateBoundary({ amount : 25350 ether, rate : 1170 }); rateBoundaries[numOfBoundaries++] = RateBoundary({ amount : 26540 ether, rate : 1160 }); rateBoundaries[numOfBoundaries++] = RateBoundary({ amount : 27730 ether, rate : 1150 }); rateBoundaries[numOfBoundaries++] = RateBoundary({ amount : 28920 ether, rate : 1140 }); rateBoundaries[numOfBoundaries++] = RateBoundary({ amount : 30110 ether, rate : 1130 }); rateBoundaries[numOfBoundaries++] = RateBoundary({ amount : 31300 ether, rate : 1120 }); rateBoundaries[numOfBoundaries++] = RateBoundary({ amount : 32490 ether, rate : 1110 }); rateBoundaries[numOfBoundaries++] = RateBoundary({ amount : 33680 ether, rate : 1100 }); rateBoundaries[numOfBoundaries++] = RateBoundary({ amount : 34870 ether, rate : 1090 }); rateBoundaries[numOfBoundaries++] = RateBoundary({ amount : 34870 ether, rate : 1080 }); rateBoundaries[numOfBoundaries++] = RateBoundary({ amount : 36060 ether, rate : 1070 }); rateBoundaries[numOfBoundaries++] = RateBoundary({ amount : 37250 ether, rate : 1060 }); rateBoundaries[numOfBoundaries++] = RateBoundary({ amount : 38440 ether, rate : 1050 }); rateBoundaries[numOfBoundaries++] = RateBoundary({ amount : 39630 ether, rate : 1040 }); rateBoundaries[numOfBoundaries++] = RateBoundary({ amount : 40820 ether, rate : 1030 }); rateBoundaries[numOfBoundaries++] = RateBoundary({ amount : 42010 ether, rate : 1020 }); rateBoundaries[numOfBoundaries++] = RateBoundary({ amount : 43200 ether, rate : 1010 }); rateBoundaries[numOfBoundaries++] = RateBoundary({ amount : 44390 ether, rate : 1000 }); nextBoundaryAmount = rateBoundaries[currentBoundary].amount; } /** * Internal method to change rate if boundary is hit */ function touchRate() internal { if (issuedTokensAmount >= nextBoundaryAmount) { currentBoundary++; if (currentBoundary >= numOfBoundaries) { nextBoundaryAmount = maxTokensAmount; } else { nextBoundaryAmount = rateBoundaries[currentBoundary].amount; tokenRate = rateBoundaries[currentBoundary].rate; } } } /** * Inherited internal method for storing tokens in contract until claim stage */ function storeTokens(address _receiver, uint256 _tokensAmount) internal whenNotPaused { ClaimableCrowdsale.storeTokens(_receiver, _tokensAmount); touchRate(); } }
* Add TORX payed by another crypto (BTC, LTC). Tokens will be stored in contract until claim stage/
function add(address _receiver, uint256 _equivalentEthAmount) onlyOwner inProgress whenNotPaused { uint256 tokensAmount = tokenRate.mul(_equivalentEthAmount); issuedTokensAmount = issuedTokensAmount.add(tokensAmount); storeTokens(_receiver, tokensAmount); TokenAdded(_receiver, tokensAmount, _equivalentEthAmount); }
12,565,229
[ 1, 986, 399, 916, 60, 8843, 329, 635, 4042, 8170, 261, 38, 15988, 16, 11807, 39, 2934, 13899, 903, 506, 4041, 316, 6835, 3180, 7516, 6009, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 527, 12, 2867, 389, 24454, 16, 2254, 5034, 389, 14298, 6505, 41, 451, 6275, 13, 1338, 5541, 316, 5491, 1347, 1248, 28590, 288, 203, 3639, 2254, 5034, 2430, 6275, 273, 1147, 4727, 18, 16411, 24899, 14298, 6505, 41, 451, 6275, 1769, 203, 3639, 16865, 5157, 6275, 273, 16865, 5157, 6275, 18, 1289, 12, 7860, 6275, 1769, 203, 203, 3639, 1707, 5157, 24899, 24454, 16, 2430, 6275, 1769, 203, 3639, 3155, 8602, 24899, 24454, 16, 2430, 6275, 16, 389, 14298, 6505, 41, 451, 6275, 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 ]
./full_match/3/0x8dF0Bb5a817210C0e27f96CDFF31c6a2497565F1/sources/browser/TorroFactory.sol
@title Factory for creation of DAOs and their governing tokens. @notice Contract for creation of DAOs and their governing tokens, and handling benefits withdrawal for all available DAO pools. @author ORayskiy - @robitnik_TorroDao
contract TorroFactory is ITorroFactory, CloneFactory { using EnumerableSet for EnumerableSet.AddressSet; uint256 private constant _customSupply = 1e22; address private _owner; address private _torroToken; address private _torroDao; mapping (address => uint256) private _benefits; mapping (address => address) private _pools; EnumerableSet.AddressSet private _poolTokens; uint256 _createPrice; uint256 _minMaxCost; event ClaimBenefits(address indexed owner); event PoolCreated(address indexed token, address indexed dao); pragma solidity 0.6.6; constructor(address torroToken_, address torroDao_) public { _owner = msg.sender; _torroToken = torroToken_; _torroDao = torroDao_; _createPrice = 2 * 10**17; _minMaxCost = 1 ether; } modifier onlyOwner() { require(_owner == msg.sender); _; } function poolTokens() public view returns (address[] memory) { uint256 length = _poolTokens.length(); address[] memory poolTokenAddresses = new address[](length); for (uint256 i = 0; i < length; i++) { poolTokenAddresses[i] = _poolTokens.at(i); } return poolTokenAddresses; } function poolTokens() public view returns (address[] memory) { uint256 length = _poolTokens.length(); address[] memory poolTokenAddresses = new address[](length); for (uint256 i = 0; i < length; i++) { poolTokenAddresses[i] = _poolTokens.at(i); } return poolTokenAddresses; } function poolDao(address token_) public view returns (address) { return _pools[token_]; } function poolTokensForHolder(address holder_) public view returns (address[] memory) { uint256 length = _poolTokens.length(); if (length == 0) { return new address[](0); } address[] memory poolTokenAddresses = new address[](length); uint256 pointer = 0; for (uint256 i = 0; i < length; i++) { address token = _poolTokens.at(i); if (token != address(0x0)) { address dao = _pools[token]; if ((ITorro(token).totalOf(holder_) > 0) || ITorroDao(dao).isPublic() || ITorroDao(dao).daoCreator() == holder_) { poolTokenAddresses[pointer++] = token; } } } return poolTokenAddresses; } function poolTokensForHolder(address holder_) public view returns (address[] memory) { uint256 length = _poolTokens.length(); if (length == 0) { return new address[](0); } address[] memory poolTokenAddresses = new address[](length); uint256 pointer = 0; for (uint256 i = 0; i < length; i++) { address token = _poolTokens.at(i); if (token != address(0x0)) { address dao = _pools[token]; if ((ITorro(token).totalOf(holder_) > 0) || ITorroDao(dao).isPublic() || ITorroDao(dao).daoCreator() == holder_) { poolTokenAddresses[pointer++] = token; } } } return poolTokenAddresses; } function poolTokensForHolder(address holder_) public view returns (address[] memory) { uint256 length = _poolTokens.length(); if (length == 0) { return new address[](0); } address[] memory poolTokenAddresses = new address[](length); uint256 pointer = 0; for (uint256 i = 0; i < length; i++) { address token = _poolTokens.at(i); if (token != address(0x0)) { address dao = _pools[token]; if ((ITorro(token).totalOf(holder_) > 0) || ITorroDao(dao).isPublic() || ITorroDao(dao).daoCreator() == holder_) { poolTokenAddresses[pointer++] = token; } } } return poolTokenAddresses; } function poolTokensForHolder(address holder_) public view returns (address[] memory) { uint256 length = _poolTokens.length(); if (length == 0) { return new address[](0); } address[] memory poolTokenAddresses = new address[](length); uint256 pointer = 0; for (uint256 i = 0; i < length; i++) { address token = _poolTokens.at(i); if (token != address(0x0)) { address dao = _pools[token]; if ((ITorro(token).totalOf(holder_) > 0) || ITorroDao(dao).isPublic() || ITorroDao(dao).daoCreator() == holder_) { poolTokenAddresses[pointer++] = token; } } } return poolTokenAddresses; } function poolTokensForHolder(address holder_) public view returns (address[] memory) { uint256 length = _poolTokens.length(); if (length == 0) { return new address[](0); } address[] memory poolTokenAddresses = new address[](length); uint256 pointer = 0; for (uint256 i = 0; i < length; i++) { address token = _poolTokens.at(i); if (token != address(0x0)) { address dao = _pools[token]; if ((ITorro(token).totalOf(holder_) > 0) || ITorroDao(dao).isPublic() || ITorroDao(dao).daoCreator() == holder_) { poolTokenAddresses[pointer++] = token; } } } return poolTokenAddresses; } function mainToken() public view override returns (address) { return _torroToken; } function mainDao() public view override returns (address) { return _torroDao; } function isDao(address dao_) public view override returns (bool) { if (dao_ == _torroDao) { return true; } uint256 length = _poolTokens.length(); for (uint256 i = 0; i < length; i++) { if (dao_ == _pools[_poolTokens.at(i)]) { return true; } } return false; } function isDao(address dao_) public view override returns (bool) { if (dao_ == _torroDao) { return true; } uint256 length = _poolTokens.length(); for (uint256 i = 0; i < length; i++) { if (dao_ == _pools[_poolTokens.at(i)]) { return true; } } return false; } function isDao(address dao_) public view override returns (bool) { if (dao_ == _torroDao) { return true; } uint256 length = _poolTokens.length(); for (uint256 i = 0; i < length; i++) { if (dao_ == _pools[_poolTokens.at(i)]) { return true; } } return false; } function isDao(address dao_) public view override returns (bool) { if (dao_ == _torroDao) { return true; } uint256 length = _poolTokens.length(); for (uint256 i = 0; i < length; i++) { if (dao_ == _pools[_poolTokens.at(i)]) { return true; } } return false; } function price() public view returns (uint256) { return _createPrice; } function benefitsOf(address sender_) public view returns (uint256) { return _benefits[sender_]; } function create(uint256 maxCost_, uint256 executeMinPct_, uint256 votingMinHours_, bool isPublic_, bool hasAdmins_) public payable { require(msg.value == _createPrice); require(maxCost_ >= _minMaxCost); address tokenProxy = createClone(_torroToken); address daoProxy = createClone(_torroDao); ITorroDao(daoProxy).initializeCustom(_torroToken, tokenProxy, address(this), msg.sender, maxCost_, executeMinPct_, votingMinHours_, isPublic_, hasAdmins_); ITorro(tokenProxy).initializeCustom(daoProxy, address(this), _customSupply); _poolTokens.add(tokenProxy); _pools[tokenProxy] = daoProxy; payable(_owner).transfer(msg.value); emit PoolCreated(tokenProxy, daoProxy); } function claimBenefits(uint256 amount_) public override { require(amount_ <= address(this).balance); uint256 amount = _benefits[msg.sender]; require(amount_ >= amount); _benefits[msg.sender] = amount - amount_; payable(msg.sender).transfer(amount_); emit ClaimBenefits(msg.sender); } function addBenefits(address recipient_, uint256 amount_) public override { require(_torroToken == msg.sender || _poolTokens.contains(msg.sender)); _benefits[recipient_] = _benefits[recipient_] + amount_; } function depositBenefits(address token_) public override payable { if (token_ == _torroToken) { require(msg.sender == _torroDao); require(_poolTokens.contains(token_) && msg.sender == _pools[token_]); } function depositBenefits(address token_) public override payable { if (token_ == _torroToken) { require(msg.sender == _torroDao); require(_poolTokens.contains(token_) && msg.sender == _pools[token_]); } } else { } function migrate(address token_) public onlyOwner { ITorroDao currentDao = ITorroDao(_pools[token_]); address daoProxy = createClone(_torroDao); ITorroDao(daoProxy).initializeCustom( _torroToken, token_, address(this), currentDao.daoCreator(), currentDao.maxCost(), currentDao.executeMinPct(), currentDao.votingMinHours(), currentDao.isPublic(), currentDao.hasAdmins() ); _pools[token_] = daoProxy; ITorro(token_).setDaoFactoryAddresses(daoProxy, address(this)); } function setPrice(uint256 price_) public onlyOwner { _createPrice = price_; } function setMinMaxCost(uint256 cost_) public onlyOwner { _minMaxCost = cost_; } function transferOwnership(address newOwner_) public onlyOwner { _owner = newOwner_; } function setNewDao(address torroDao_) public onlyOwner { _torroDao = torroDao_; } }
8,149,530
[ 1, 1733, 364, 6710, 434, 463, 37, 15112, 471, 3675, 314, 1643, 2093, 2430, 18, 225, 13456, 364, 6710, 434, 463, 37, 15112, 471, 3675, 314, 1643, 2093, 2430, 16, 471, 5057, 27641, 18352, 598, 9446, 287, 364, 777, 2319, 463, 20463, 16000, 18, 225, 4869, 528, 7771, 77, 93, 300, 632, 303, 3682, 82, 1766, 67, 27266, 303, 11412, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 23763, 303, 1733, 353, 24142, 280, 303, 1733, 16, 12758, 1733, 288, 203, 225, 1450, 6057, 25121, 694, 364, 6057, 25121, 694, 18, 1887, 694, 31, 203, 203, 225, 2254, 5034, 3238, 5381, 389, 3662, 3088, 1283, 273, 404, 73, 3787, 31, 203, 225, 1758, 3238, 389, 8443, 31, 203, 225, 1758, 3238, 389, 13039, 303, 1345, 31, 203, 225, 1758, 3238, 389, 13039, 303, 11412, 31, 203, 225, 2874, 261, 2867, 516, 2254, 5034, 13, 3238, 389, 70, 4009, 18352, 31, 203, 225, 2874, 261, 2867, 516, 1758, 13, 3238, 389, 27663, 31, 203, 225, 6057, 25121, 694, 18, 1887, 694, 3238, 389, 6011, 5157, 31, 203, 225, 2254, 5034, 389, 2640, 5147, 31, 203, 225, 2254, 5034, 389, 1154, 2747, 8018, 31, 203, 21281, 225, 871, 18381, 38, 4009, 18352, 12, 2867, 8808, 3410, 1769, 203, 203, 202, 2575, 8828, 6119, 12, 2867, 8808, 1147, 16, 1758, 8808, 15229, 1769, 203, 203, 683, 9454, 18035, 560, 374, 18, 26, 18, 26, 31, 203, 225, 3885, 12, 2867, 8934, 303, 1345, 67, 16, 1758, 8934, 303, 11412, 67, 13, 1071, 288, 203, 565, 389, 8443, 273, 1234, 18, 15330, 31, 203, 565, 389, 13039, 303, 1345, 273, 8934, 303, 1345, 67, 31, 203, 565, 389, 13039, 303, 11412, 273, 8934, 303, 11412, 67, 31, 203, 565, 389, 2640, 5147, 273, 576, 380, 1728, 636, 4033, 31, 203, 565, 389, 1154, 2747, 8018, 273, 404, 225, 2437, 31, 203, 225, 289, 203, 203, 225, 9606, 1338, 5541, 1435, 288, 203, 565, 2583, 24899, 2 ]
./full_match/80001/0xb52b844F9c9481Bcb8CdDb44e6E8322267627fb6/sources/circuit_v2/contract/main/plonk_vk.sol
VALIDATE Q2 validate on curve
{ let x := mload(Q2_X_LOC) let y := mload(Q2_Y_LOC) let xx := mulmod(x, x, q) success := and(success, eq(mulmod(y, y, q), addmod(mulmod(x, xx, q), 3, q))) mstore(0x00, x) mstore(0x20, y) success := and(success, staticcall(gas(), 7, 0x00, 0x60, ACCUMULATOR2_X_LOC, 0x40)) success := and(success, staticcall(gas(), 6, ACCUMULATOR_X_LOC, 0x80, ACCUMULATOR_X_LOC, 0x40)) }
877,421
[ 1, 14687, 2238, 22, 1954, 603, 8882, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5411, 288, 203, 7734, 2231, 619, 519, 312, 945, 12, 53, 22, 67, 60, 67, 29450, 13, 203, 7734, 2231, 677, 519, 312, 945, 12, 53, 22, 67, 61, 67, 29450, 13, 203, 7734, 2231, 12223, 519, 14064, 1711, 12, 92, 16, 619, 16, 1043, 13, 203, 7734, 2216, 519, 471, 12, 4768, 16, 7555, 12, 16411, 1711, 12, 93, 16, 677, 16, 1043, 3631, 527, 1711, 12, 16411, 1711, 12, 92, 16, 12223, 16, 1043, 3631, 890, 16, 1043, 20349, 203, 7734, 312, 2233, 12, 20, 92, 713, 16, 619, 13, 203, 7734, 312, 2233, 12, 20, 92, 3462, 16, 677, 13, 203, 5411, 2216, 519, 471, 12, 4768, 16, 760, 1991, 12, 31604, 9334, 2371, 16, 374, 92, 713, 16, 374, 92, 4848, 16, 18816, 2799, 1506, 3575, 22, 67, 60, 67, 29450, 16, 374, 92, 7132, 3719, 203, 5411, 2216, 519, 471, 12, 4768, 16, 760, 1991, 12, 31604, 9334, 1666, 16, 18816, 2799, 1506, 3575, 67, 60, 67, 29450, 16, 374, 92, 3672, 16, 18816, 2799, 1506, 3575, 67, 60, 67, 29450, 16, 374, 92, 7132, 3719, 203, 5411, 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 ]
// SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.0; import "hardhat/console.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "./MemberManager.sol"; import "./ProposalManager.sol"; /** * This contract is to create dao easier than pesent methmod. * - When you create your own dao, you can get a NFT what prove to be a dao member. */ contract SubDAO is ReentrancyGuard{ using Counters for Counters.Counter; Counters.Counter private _contributeIdTracker; Counters.Counter private _tokenIdTracker; MemberManagerInterface private memberManagerContract; ProposalManagerInterface private proposalManagerContract; string public daoName; string public githubURL; uint256 public amountOfDotation; address private erc721Address; address private owner; struct ContributeInfo { address eoa; string githubURL; } enum TokenKind { erc20, erm721 } struct TokenInfo { TokenKind tokenKind; address tokenAddress; } event ReportedContribution(address indexed eoa, string githubURL, uint256 reportId); event Donated(address indexed eoa, uint256 amount); event Divided(address indexed eoa, address to, uint256 amount); // contoribute id => ContributeInfo mapping(uint256 => ContributeInfo) public contributionReports; // tokenId => token info mapping(uint256 => TokenInfo) public tokenList; /** * コンストラクター */ constructor(string memory _daoName, string memory _githubURL, address _memberManager, address _proposalManger, address _memberNFTAddress){ // initial increment _contributeIdTracker.increment(); _tokenIdTracker.increment(); daoName = _daoName; githubURL = _githubURL; owner = msg.sender; erc721Address = _memberNFTAddress; memberManagerContract = MemberManagerInterface(_memberManager); proposalManagerContract = ProposalManagerInterface(_proposalManger); } /** * オーナーを取得する */ function getOwnerAddress() public view returns(address) { return owner; } /** * SubDAOに関連付けられたメンバーNFTのアドレスを取得する */ function getMemberNFTAddress() public view onlyMember returns (address) { return erc721Address; } /** * 貢献の活動をレポートする。 */ function reportContribution(string memory _githubURL) public { require(bytes(_githubURL).length!=0,"invalid url."); contributionReports[_contributeIdTracker.current()]=ContributeInfo(msg.sender,_githubURL); emit ReportedContribution(msg.sender, _githubURL, _contributeIdTracker.current()); _contributeIdTracker.increment(); } /** * 活動の一覧を取得する */ function getContributionList() public view returns (ContributeInfo[] memory) { ContributeInfo[] memory contoributionList = new ContributeInfo[](_contributeIdTracker.current() - 1); for (uint256 i=1; i < _contributeIdTracker.current(); i++) { if (bytes(contributionReports[i].githubURL).length!=0){ contoributionList[i-1] = contributionReports[i]; } } return contoributionList; } /** * 寄付を受け付ける */ function donate() public payable { amountOfDotation += msg.value; emit Donated(msg.sender, msg.value); } /** * 分配する */ function divide(address to, uint256 amount, uint256 _relatedProposalId) public payable onlyMember { ProposalInfo memory info = proposalManagerContract.getPropsalInfo(address(this), _relatedProposalId); require(info.proposalKind==ProposalKind.UseOfFunds,"invalid proposalKind."); require(info.relatedAddress==to,"Not proposed."); require(info.proposalStatus==ProposalStatus.Running,"Not approved."); payable(to).transfer(amount); proposalManagerContract.updateProposalStatus(address(this), _relatedProposalId, uint(ProposalStatus.Finished)); emit Divided(msg.sender, to, amount); } /** * contract addressの残高を確認する */ function getContractBalance() public view returns(uint256) { return address(this).balance; } /** * Token Listに追加する */ function addTokenToList(TokenKind _tokenKind, address _tokenAddress) public onlyMember { tokenList[_tokenIdTracker.current()]=TokenInfo(_tokenKind,_tokenAddress); _tokenIdTracker.increment(); } /** * Token Listを取得する */ function getTokenList() public view returns(TokenInfo[] memory) { TokenInfo[] memory _tokenList = new TokenInfo[](_tokenIdTracker.current() - 1); for (uint256 i=1; i < _tokenIdTracker.current(); i++) { if (tokenList[i].tokenAddress!=address(0)){ _tokenList[i-1] = tokenList[i]; } } return _tokenList; } /** * 入金を受け取る */ receive() external payable {} /** * オーナーを取得する */ function getOwner() external view returns(address) { if (msg.sender==tx.origin){ require(msg.sender==owner,"only owner does."); } return owner; } /** * メンバーのみチェック */ modifier onlyMember(){ require(memberManagerContract.isMember(address(this),msg.sender),"only member does."); _; } /** * オーナーチェック */ modifier onlyOwner(){ require(msg.sender == owner); _; } }
contoribute id => ContributeInfo
mapping(uint256 => ContributeInfo) public contributionReports;
12,711,668
[ 1, 1213, 280, 495, 624, 612, 516, 735, 887, 966, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 2874, 12, 11890, 5034, 516, 735, 887, 966, 13, 1071, 24880, 18631, 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 ]
./full_match/1/0xEe83F8eBB435373f6c231173995cC990697af1B8/sources/contracts/utils/InitializableAbstractStrategy.sol
Core address for the given platform asset => pToken (Platform Specific Token Address) Full list of all assets supported here Deprecated: Reward token address slither-disable-next-line constable-states Deprecated: now resides in Harvester's rewardTokenConfigs slither-disable-next-line constable-states Address of the one address allowed to collect reward tokens Reward token addresses Reserved for future expansion
abstract contract InitializableAbstractStrategy is Initializable, Governable { using SafeERC20 for IERC20; using SafeMath for uint256; event PTokenAdded(address indexed _asset, address _pToken); event PTokenRemoved(address indexed _asset, address _pToken); event Deposit(address indexed _asset, address _pToken, uint256 _amount); event Withdrawal(address indexed _asset, address _pToken, uint256 _amount); event RewardTokenCollected( address recipient, address rewardToken, uint256 amount ); event RewardTokenAddressesUpdated( address[] _oldAddresses, address[] _newAddresses ); event HarvesterAddressesUpdated( address _oldHarvesterAddress, address _newHarvesterAddress ); address public platformAddress; address public vaultAddress; mapping(address => address) public assetToPToken; address[] internal assetsMapped; address public _deprecated_rewardTokenAddress; uint256 public _deprecated_rewardLiquidationThreshold; address public harvesterAddress; address[] public rewardTokenAddresses; int256[98] private _reserved; function initialize( address _platformAddress, address _vaultAddress, address[] calldata _rewardTokenAddresses, address[] calldata _assets, address[] calldata _pTokens pragma solidity ^0.8.0; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import { SafeMath } from "@openzeppelin/contracts/utils/math/SafeMath.sol"; import { Initializable } from "../utils/Initializable.sol"; import { Governable } from "../governance/Governable.sol"; ) external onlyGovernor initializer { InitializableAbstractStrategy._initialize( _platformAddress, _vaultAddress, _rewardTokenAddresses, _assets, _pTokens ); } function _initialize( address _platformAddress, address _vaultAddress, address[] calldata _rewardTokenAddresses, address[] memory _assets, address[] memory _pTokens ) internal { platformAddress = _platformAddress; vaultAddress = _vaultAddress; rewardTokenAddresses = _rewardTokenAddresses; uint256 assetCount = _assets.length; require(assetCount == _pTokens.length, "Invalid input arrays"); for (uint256 i = 0; i < assetCount; i++) { _setPTokenAddress(_assets[i], _pTokens[i]); } } function _initialize( address _platformAddress, address _vaultAddress, address[] calldata _rewardTokenAddresses, address[] memory _assets, address[] memory _pTokens ) internal { platformAddress = _platformAddress; vaultAddress = _vaultAddress; rewardTokenAddresses = _rewardTokenAddresses; uint256 assetCount = _assets.length; require(assetCount == _pTokens.length, "Invalid input arrays"); for (uint256 i = 0; i < assetCount; i++) { _setPTokenAddress(_assets[i], _pTokens[i]); } } function collectRewardTokens() external virtual onlyHarvester nonReentrant { _collectRewardTokens(); } function _collectRewardTokens() internal { for (uint256 i = 0; i < rewardTokenAddresses.length; i++) { IERC20 rewardToken = IERC20(rewardTokenAddresses[i]); uint256 balance = rewardToken.balanceOf(address(this)); emit RewardTokenCollected( harvesterAddress, rewardTokenAddresses[i], balance ); rewardToken.safeTransfer(harvesterAddress, balance); } } function _collectRewardTokens() internal { for (uint256 i = 0; i < rewardTokenAddresses.length; i++) { IERC20 rewardToken = IERC20(rewardTokenAddresses[i]); uint256 balance = rewardToken.balanceOf(address(this)); emit RewardTokenCollected( harvesterAddress, rewardTokenAddresses[i], balance ); rewardToken.safeTransfer(harvesterAddress, balance); } } modifier onlyVault() { require(msg.sender == vaultAddress, "Caller is not the Vault"); _; } modifier onlyHarvester() { require(msg.sender == harvesterAddress, "Caller is not the Harvester"); _; } modifier onlyVaultOrGovernor() { require( msg.sender == vaultAddress || msg.sender == governor(), "Caller is not the Vault or Governor" ); _; } function setRewardTokenAddresses(address[] calldata _rewardTokenAddresses) external onlyGovernor { for (uint256 i = 0; i < _rewardTokenAddresses.length; i++) { require( _rewardTokenAddresses[i] != address(0), "Can not set an empty address as a reward token" ); } emit RewardTokenAddressesUpdated( rewardTokenAddresses, _rewardTokenAddresses ); rewardTokenAddresses = _rewardTokenAddresses; } function setRewardTokenAddresses(address[] calldata _rewardTokenAddresses) external onlyGovernor { for (uint256 i = 0; i < _rewardTokenAddresses.length; i++) { require( _rewardTokenAddresses[i] != address(0), "Can not set an empty address as a reward token" ); } emit RewardTokenAddressesUpdated( rewardTokenAddresses, _rewardTokenAddresses ); rewardTokenAddresses = _rewardTokenAddresses; } function getRewardTokenAddresses() external view returns (address[] memory) { return rewardTokenAddresses; } function setPTokenAddress(address _asset, address _pToken) external onlyGovernor { _setPTokenAddress(_asset, _pToken); } function removePToken(uint256 _assetIndex) external onlyGovernor { require(_assetIndex < assetsMapped.length, "Invalid index"); address asset = assetsMapped[_assetIndex]; address pToken = assetToPToken[asset]; if (_assetIndex < assetsMapped.length - 1) { assetsMapped[_assetIndex] = assetsMapped[assetsMapped.length - 1]; } assetsMapped.pop(); assetToPToken[asset] = address(0); emit PTokenRemoved(asset, pToken); } function removePToken(uint256 _assetIndex) external onlyGovernor { require(_assetIndex < assetsMapped.length, "Invalid index"); address asset = assetsMapped[_assetIndex]; address pToken = assetToPToken[asset]; if (_assetIndex < assetsMapped.length - 1) { assetsMapped[_assetIndex] = assetsMapped[assetsMapped.length - 1]; } assetsMapped.pop(); assetToPToken[asset] = address(0); emit PTokenRemoved(asset, pToken); } function _setPTokenAddress(address _asset, address _pToken) internal { require(assetToPToken[_asset] == address(0), "pToken already set"); require( _asset != address(0) && _pToken != address(0), "Invalid addresses" ); assetToPToken[_asset] = _pToken; assetsMapped.push(_asset); emit PTokenAdded(_asset, _pToken); _abstractSetPToken(_asset, _pToken); } function transferToken(address _asset, uint256 _amount) public onlyGovernor { IERC20(_asset).safeTransfer(governor(), _amount); } function setHarvesterAddress(address _harvesterAddress) external onlyGovernor { harvesterAddress = _harvesterAddress; emit HarvesterAddressesUpdated(harvesterAddress, _harvesterAddress); } Abstract }
3,080,432
[ 1, 4670, 1758, 364, 326, 864, 4072, 3310, 516, 293, 1345, 261, 8201, 23043, 3155, 5267, 13, 11692, 666, 434, 777, 7176, 3260, 2674, 9336, 30, 534, 359, 1060, 1147, 1758, 2020, 2927, 17, 8394, 17, 4285, 17, 1369, 1866, 429, 17, 7992, 9336, 30, 2037, 400, 4369, 316, 670, 297, 3324, 387, 1807, 19890, 1345, 8062, 2020, 2927, 17, 8394, 17, 4285, 17, 1369, 1866, 429, 17, 7992, 5267, 434, 326, 1245, 1758, 2935, 358, 3274, 19890, 2430, 534, 359, 1060, 1147, 6138, 16237, 364, 3563, 17965, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 17801, 6835, 10188, 6934, 7469, 4525, 353, 10188, 6934, 16, 611, 1643, 6914, 288, 203, 565, 1450, 14060, 654, 39, 3462, 364, 467, 654, 39, 3462, 31, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 565, 871, 453, 1345, 8602, 12, 2867, 8808, 389, 9406, 16, 1758, 389, 84, 1345, 1769, 203, 565, 871, 453, 1345, 10026, 12, 2867, 8808, 389, 9406, 16, 1758, 389, 84, 1345, 1769, 203, 565, 871, 4019, 538, 305, 12, 2867, 8808, 389, 9406, 16, 1758, 389, 84, 1345, 16, 2254, 5034, 389, 8949, 1769, 203, 565, 871, 3423, 9446, 287, 12, 2867, 8808, 389, 9406, 16, 1758, 389, 84, 1345, 16, 2254, 5034, 389, 8949, 1769, 203, 565, 871, 534, 359, 1060, 1345, 10808, 329, 12, 203, 3639, 1758, 8027, 16, 203, 3639, 1758, 19890, 1345, 16, 203, 3639, 2254, 5034, 3844, 203, 565, 11272, 203, 565, 871, 534, 359, 1060, 1345, 7148, 7381, 12, 203, 3639, 1758, 8526, 389, 1673, 7148, 16, 203, 3639, 1758, 8526, 389, 2704, 7148, 203, 565, 11272, 203, 565, 871, 670, 297, 3324, 387, 7148, 7381, 12, 203, 3639, 1758, 389, 1673, 44, 297, 3324, 387, 1887, 16, 203, 3639, 1758, 389, 2704, 44, 297, 3324, 387, 1887, 203, 565, 11272, 203, 203, 565, 1758, 1071, 4072, 1887, 31, 203, 203, 565, 1758, 1071, 9229, 1887, 31, 203, 203, 565, 2874, 12, 2867, 516, 1758, 13, 1071, 3310, 774, 52, 1345, 31, 203, 203, 565, 1758, 8526, 2713, 7176, 12868, 31, 203, 203, 565, 1758, 1071, 389, 14089, 67, 2 ]
./full_match/5/0xcB3FDf376a1625C4c4a1398f30C457572EC0e31c/sources/verified-sources/0x68d7978419893ce1EE35Ff411B9D9C90196D70F1/sources/contracts/feature/Ownable.sol
@dev Lets a contract admin set a new owner for the contract. The new owner must be a contract admin.
function _setupOwner(address _newOwner) internal { address _prevOwner = owner; owner = _newOwner; emit OwnerUpdated(_prevOwner, _newOwner); }
1,853,940
[ 1, 48, 2413, 279, 6835, 3981, 444, 279, 394, 3410, 364, 326, 6835, 18, 1021, 394, 3410, 1297, 506, 279, 6835, 3981, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 8401, 5541, 12, 2867, 389, 2704, 5541, 13, 2713, 288, 203, 3639, 1758, 389, 10001, 5541, 273, 3410, 31, 203, 3639, 3410, 273, 389, 2704, 5541, 31, 203, 203, 3639, 3626, 16837, 7381, 24899, 10001, 5541, 16, 389, 2704, 5541, 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 ]
./partial_match/8453/0x8a7878Cd64cBCD1fa997ed45fDb840ffC572cB18/sources/contracts/DataStorageOperator.sol
@inheritdoc IDataStorageOperator
function changeFeeConfiguration(AdaptiveFee.Configuration calldata _feeConfig) external override { require(msg.sender == factory || msg.sender == IAlgebraFactory(factory).owner()); require(uint256(_feeConfig.alpha1) + uint256(_feeConfig.alpha2) + uint256(_feeConfig.baseFee) <= type(uint16).max, 'Max fee exceeded'); require(_feeConfig.gamma1 != 0 && _feeConfig.gamma2 != 0 && _feeConfig.volumeGamma != 0, 'Gammas must be > 0'); feeConfig = _feeConfig; emit FeeConfiguration(_feeConfig); }
16,762,089
[ 1, 36, 10093, 467, 751, 3245, 5592, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 2549, 14667, 1750, 12, 13716, 688, 14667, 18, 1750, 745, 892, 389, 21386, 809, 13, 3903, 3849, 288, 203, 565, 2583, 12, 3576, 18, 15330, 422, 3272, 747, 1234, 18, 15330, 422, 467, 1067, 29087, 1733, 12, 6848, 2934, 8443, 10663, 203, 203, 565, 2583, 12, 11890, 5034, 24899, 21386, 809, 18, 5429, 21, 13, 397, 2254, 5034, 24899, 21386, 809, 18, 5429, 22, 13, 397, 2254, 5034, 24899, 21386, 809, 18, 1969, 14667, 13, 1648, 618, 12, 11890, 2313, 2934, 1896, 16, 296, 2747, 14036, 12428, 8284, 203, 565, 2583, 24899, 21386, 809, 18, 20589, 21, 480, 374, 597, 389, 21386, 809, 18, 20589, 22, 480, 374, 597, 389, 21386, 809, 18, 9491, 31300, 480, 374, 16, 296, 43, 301, 15260, 1297, 506, 405, 374, 8284, 203, 203, 565, 14036, 809, 273, 389, 21386, 809, 31, 203, 565, 3626, 30174, 1750, 24899, 21386, 809, 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 ]
// SPDX-License-Identifier: MIT pragma solidity 0.8.6; import "@openzeppelin/contracts/utils/Context.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/security/Pausable.sol"; import "./interfaces/IPancakeRouter02.sol"; import "./interfaces/IAlpacaToken.sol"; import "hardhat/console.sol"; interface IFarm { function userInfo(uint256 _pid, address _user) external view returns (uint256 amount, uint256 rewardDebt, uint256 bonusDebt, uint256 fundedBy); } interface ITreasury { function notifyExternalReward(uint256 _amount) external; } interface IFairLaunch { function pendingAlpaca(uint256 _pid, address _user) external view returns (uint256); function deposit(address _for, uint256 _pid, uint256 _amount) external; function withdraw(address _for, uint256 _pid, uint256 _amount) external; function withdrawAll(address _for, uint256 _pid) external; function harvest(uint256 _pid) external; } interface IVault { /// @dev Add more ERC20 to the bank. Hope to get some good returns. function deposit(uint256 amountToken) external; /// @dev Withdraw ERC20 from the bank by burning the share tokens. function withdraw(uint256 share) external; } contract iSwapStrategyAlpaca is Ownable, ReentrancyGuard, Pausable { using SafeMath for uint256; using SafeERC20 for IERC20; bool public isAutoComp; // this vault is purely for staking. eg. WBNB-BDO staking vault. bool public strategyStopped = false; bool public checkForUnlockReward = false; address public vaultContractAddress; // address of vault. address public farmContractAddress; // address of farm, eg, PCS, Thugs etc. uint256 public pid; // pid of pool in farmContractAddress address public wantAddress; address public earnedAddress; address public routerAddress = address(0x10ED43C718714eb63d5aA57B78B54704E256024E); // PancakeSwap: Router address public operator; address public strategist; bool public notPublic = false; // allow public to call earn() function uint256 public lastEarnBlock = 0; uint256 public wantLockedTotal = 0; uint256 public sharesTotal = 0; uint256 public controllerFee = 100; // 100 = 1% uint256 public constant CONTROLLER_FEE_UL = 100; // 0.5% is the max entrance fee settable. UL = upper limit uint256 public constant CONTROLLER_FEE_DENOMINATOR = 10000; uint256 public entranceFeeFactor = 0; // 0% entrance fee (goes to pool + prevents front-running) uint256 public constant ENTRANCE_FEE_FACTOR_MAX = 10000; // 100 = 1% uint256 public constant ENTRANCE_FEE_FACTOR_LL = 500; // 0.5% is the max entrance fee settable. LL = lower limit address[] public earnedToWantPath; address[] public earnedToBusdPath; address[] public wantToEarnedPath; event Deposit(uint256 amount); event Withdraw(uint256 amount); event Farm(uint256 amount); event Compound(address token0Address, uint256 token0Amt, address token1Address, uint256 token1Amt); event Earned(address earnedAddress, uint256 earnedAmt); event BuyBack(address earnedAddress, address buyBackToken, uint256 earnedAmt, uint256 buyBackAmt, address receiver); event DistributeFee(address earnedAddress, uint256 fee, address receiver); event ConvertDustToEarned(address tokenAddress, address earnedAddress, uint256 tokenAmt); event InCaseTokensGetStuck(address tokenAddress, uint256 tokenAmt, address receiver); event ExecuteTransaction(address indexed target, uint256 value, string signature, bytes data); // _controller: iVaultBank // _buyBackToken1Info[]: buyBackToken1, buyBackAddress1, buyBackToken1MidRouteAddress // _buyBackToken2Info[]: buyBackToken2, buyBackAddress2, buyBackToken2MidRouteAddress // _token0Info[]: token0Address, token0MidRouteAddress // _token1Info[]: token1Address, token1MidRouteAddress constructor( address _controller, bool _isAutoComp, address _vaultContractAddress, address _farmContractAddress, uint256 _pid, address _wantAddress, address _earnedAddress, address _routerAddress ) { operator = msg.sender; strategist = msg.sender; // to call earn if public not allowed isAutoComp = _isAutoComp; wantAddress = _wantAddress; if (_routerAddress != address(0)) routerAddress = _routerAddress; if (isAutoComp) { vaultContractAddress = _vaultContractAddress; farmContractAddress = _farmContractAddress; pid = _pid; earnedAddress = _earnedAddress; routerAddress = _routerAddress; earnedToBusdPath = [_earnedAddress, address(0xe9e7CEA3DedcA5984780Bafc599bD69ADd087D56)]; // BUSD Address earnedToWantPath = [_earnedAddress, _wantAddress]; wantToEarnedPath = [_wantAddress, _earnedAddress]; } transferOwnership(_controller); } receive() external payable {} fallback() external payable {} modifier onlyOperator() { require(operator == msg.sender, "iSwapStrategyAlpaca: caller is not the operator"); _; } modifier onlyStrategist() { require(strategist == msg.sender || operator == msg.sender, "iSwapStrategyAlpaca: caller is not the strategist"); _; } modifier strategyRunning() { require(!strategyStopped, "iSwapStrategyAlpaca: strategy is not running"); _; } function isAuthorised(address _account) public view returns (bool) { return (_account == operator) || (msg.sender == strategist); } // Receives new deposits from user function deposit(address, uint256 _wantAmt) public onlyOwner whenNotPaused strategyRunning returns (uint256) { IERC20(wantAddress).safeTransferFrom(address(msg.sender), address(this), _wantAmt); uint256 sharesAdded = _wantAmt; if (wantLockedTotal > 0) { sharesAdded = _wantAmt * sharesTotal * entranceFeeFactor / wantLockedTotal / ENTRANCE_FEE_FACTOR_MAX; } sharesTotal = sharesTotal + sharesAdded; if (isAutoComp) { _farm(); } else { wantLockedTotal = wantLockedTotal + _wantAmt; } emit Deposit(_wantAmt); return sharesAdded; } function farm() public nonReentrant strategyRunning { _farm(); } function _farm() internal { // add to vault to get ibToken uint256 wantAmt = IERC20(wantAddress).balanceOf(address(this)); wantLockedTotal = wantLockedTotal + wantAmt; IERC20(wantAddress).safeIncreaseAllowance(vaultContractAddress, wantAmt); IVault(vaultContractAddress).deposit(wantAmt); // add ibToken to farm contract uint256 ibWantAmt = IERC20(vaultContractAddress).balanceOf(address(this)); IERC20(vaultContractAddress).safeIncreaseAllowance(farmContractAddress, ibWantAmt); IFairLaunch(farmContractAddress).deposit(address(this), pid, ibWantAmt); emit Farm(wantAmt); } function withdraw(address, uint256 _wantAmt) public onlyOwner nonReentrant returns (uint256) { require(_wantAmt > 0, "iSwapStrategyAlpaca: !_wantAmt"); if (isAutoComp && !strategyStopped) { IFairLaunch(farmContractAddress).withdraw(address(this), pid, _wantAmt); IVault(vaultContractAddress).withdraw(_wantAmt); } uint256 wantAmt = IERC20(wantAddress).balanceOf(address(this)); if (_wantAmt > wantAmt) { _wantAmt = wantAmt; } if (wantLockedTotal < _wantAmt) { _wantAmt = wantLockedTotal; } uint256 sharesRemoved = _wantAmt * sharesTotal / wantLockedTotal; if (sharesRemoved > sharesTotal) { sharesRemoved = sharesTotal; } sharesTotal = sharesTotal - sharesRemoved; wantLockedTotal = wantLockedTotal - _wantAmt; IERC20(wantAddress).safeTransfer(address(msg.sender), _wantAmt); emit Withdraw(_wantAmt); return sharesRemoved; } // 1. Harvest farm tokens // 2. Converts farm tokens into want tokens // 3. Deposits want tokens function earn() public whenNotPaused { require(isAutoComp, "iSwapStrategyAlpaca: !isAutoComp"); require(!notPublic || isAuthorised(msg.sender), "iSwapStrategyAlpaca: !authorised"); // Harvest farm tokens IFairLaunch(farmContractAddress).harvest(pid); // Check if there is any unlocked amount if (checkForUnlockReward) { if (IAlpacaToken(earnedAddress).canUnlockAmount(address(this)) > 0) { IAlpacaToken(earnedAddress).unlock(); } } // Converts farm tokens into want tokens uint256 earnedAmt = IERC20(earnedAddress).balanceOf(address(this)); emit Earned(earnedAddress, earnedAmt); uint256 _distributeFee = distributeFees(earnedAmt); earnedAmt = earnedAmt - _distributeFee; IERC20(earnedAddress).safeIncreaseAllowance(routerAddress, earnedAmt); if (earnedAddress != wantAddress) { // Swap half earned to token0 IPancakeRouter02(routerAddress).swapExactTokensForTokensSupportingFeeOnTransferTokens(earnedAmt, 0, earnedToWantPath, address(this), block.timestamp + 60); } // Get want tokens, ie. add liquidity uint256 wantAmt = IERC20(wantAddress).balanceOf(address(this)); if (wantAmt > 0) { emit Compound(wantAddress, wantAmt, address (0), 0); } lastEarnBlock = block.number; _farm(); } function distributeFees(uint256 _earnedAmt) internal returns (uint256 _fee) { if (_earnedAmt > 0) { // Performance fee if (controllerFee > 0) { _fee = _earnedAmt * controllerFee / CONTROLLER_FEE_DENOMINATOR; IERC20(earnedAddress).safeTransfer(operator, _fee); emit DistributeFee(earnedAddress, _fee, operator); } } } function convertDustToEarned() public whenNotPaused { require(isAutoComp, "iSwapStrategyAlpaca: !isAutoComp"); // Converts dust tokens into earned tokens, which will be reinvested on the next earn(). // Converts token0 dust (if any) to earned tokens uint256 wantAmt = IERC20(wantAddress).balanceOf(address(this)); if (wantAddress != earnedAddress && wantAmt > 0) { IERC20(wantAddress).safeIncreaseAllowance(routerAddress, wantAmt); // Swap all dust tokens to earned tokens IPancakeRouter02(routerAddress).swapExactTokensForTokensSupportingFeeOnTransferTokens(wantAmt, 0, wantToEarnedPath, address(this), block.timestamp + 60); emit ConvertDustToEarned(wantAddress, earnedAddress, wantAmt); } } function uniExchangeRate(uint256 _tokenAmount, address[] memory _path) public view returns (uint256) { uint256[] memory amounts = IPancakeRouter02(routerAddress).getAmountsOut(_tokenAmount, _path); return amounts[amounts.length - 1]; } function pendingHarvest() public view returns (uint256) { uint256 _earnedBal = IERC20(earnedAddress).balanceOf(address(this)); return IFairLaunch(farmContractAddress).pendingAlpaca(pid, address(this)) + _earnedBal; } function pendingHarvestDollarValue() public view returns (uint256) { uint256 _pending = pendingHarvest(); return (_pending == 0) ? 0 : uniExchangeRate(_pending, earnedToBusdPath); } function balanceInPool() public view returns (uint256) { (uint256 amount, , , ) = IFarm(farmContractAddress).userInfo(pid, address (this)); return amount; } function pause() external onlyOperator { _pause(); } function unpause() external onlyOperator { _unpause(); } function setOperator(address _operator) external onlyOperator { operator = _operator; } function setStrategist(address _strategist) external onlyOperator { strategist = _strategist; } function setEntranceFeeFactor(uint256 _entranceFeeFactor) external onlyOperator { require(_entranceFeeFactor > ENTRANCE_FEE_FACTOR_LL, "iSwapStrategyAlpaca: !safe - too low"); require(_entranceFeeFactor <= ENTRANCE_FEE_FACTOR_MAX, "iSwapStrategyAlpaca: !safe - too high"); entranceFeeFactor = _entranceFeeFactor; } function setControllerFee(uint256 _controllerFee) external onlyOperator { require(_controllerFee <= CONTROLLER_FEE_UL, "iSwapStrategyAlpaca: too high"); controllerFee = _controllerFee; } function setNotPublic(bool _notPublic) external onlyOperator { notPublic = _notPublic; } function setCheckForUnlockReward(bool _checkForUnlockReward) external onlyOperator { checkForUnlockReward = _checkForUnlockReward; } function setRouterAddress(address _routerAddress) external onlyOperator { routerAddress = _routerAddress; } function inCaseTokensGetStuck(address _token, uint256 _amount, address _to) external onlyOperator { require(_token != earnedAddress, "!safe"); require(_token != wantAddress, "!safe"); IERC20(_token).safeTransfer(_to, _amount); emit InCaseTokensGetStuck(_token, _amount, _to); } function emergencyWithraw() external onlyOperator { (uint256 _wantAmt, , , ) = IFarm(farmContractAddress).userInfo(pid, address (this)); IFairLaunch(farmContractAddress).withdraw(address(this), pid, _wantAmt); IVault(vaultContractAddress).withdraw(_wantAmt); strategyStopped = true; } function resumeStrategy() external onlyOperator { strategyStopped = false; farm(); } }
0.5% is the max entrance fee settable. LL = lower limit
uint256 public constant ENTRANCE_FEE_FACTOR_LL = 500;
13,068,879
[ 1, 20, 18, 25, 9, 353, 326, 943, 31976, 1359, 14036, 444, 2121, 18, 29863, 273, 2612, 1800, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 2254, 5034, 1071, 5381, 8348, 54, 4722, 67, 8090, 41, 67, 26835, 67, 4503, 273, 6604, 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 ]
pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // File: @openzeppelin/contracts/utils/Counters.sol // OpenZeppelin Contracts v4.4.1 (utils/Counters.sol) pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // File: @openzeppelin/contracts/security/ReentrancyGuard.sol // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol // OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts/interfaces/IERC20.sol // OpenZeppelin Contracts v4.4.1 (interfaces/IERC20.sol) pragma solidity ^0.8.0; // File: @openzeppelin/contracts/utils/Strings.sol // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: @openzeppelin/contracts/utils/Context.sol // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: @openzeppelin/contracts/access/Ownable.sol // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File: @openzeppelin/contracts/utils/Address.sol // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File: @openzeppelin/contracts/utils/introspection/IERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/interfaces/IERC165.sol // OpenZeppelin Contracts v4.4.1 (interfaces/IERC165.sol) pragma solidity ^0.8.0; // File: @openzeppelin/contracts/interfaces/IERC2981.sol // OpenZeppelin Contracts v4.4.1 (interfaces/IERC2981.sol) pragma solidity ^0.8.0; /** * @dev Interface for the NFT Royalty Standard */ interface IERC2981 is IERC165 { /** * @dev Called with the sale price to determine how much royalty is owed and to whom. * @param tokenId - the NFT asset queried for royalty information * @param salePrice - the sale price of the NFT asset specified by `tokenId` * @return receiver - address of who should be sent the royalty payment * @return royaltyAmount - the royalty payment amount for `salePrice` */ function royaltyInfo(uint256 tokenId, uint256 salePrice) external view returns (address receiver, uint256 royaltyAmount); } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: @openzeppelin/contracts/token/ERC721/ERC721.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. 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: coven/vapes.sol //SPDX-License-Identifier: MIT //Contract based on [https://docs.openzeppelin.com/contracts/3.x/erc721](https://docs.openzeppelin.com/contracts/3.x/erc721) pragma solidity ^0.8.0; contract CryptoDungeons is ERC721, IERC2981, Ownable, ReentrancyGuard { using Counters for Counters.Counter; using Strings for uint256; Counters.Counter private tokenCounter; string private baseURI = "https://gateway.pinata.cloud/ipfs/QmTBZJK4WaoLYBSpXb3DLfHAqwJ7z8VjaqrLCa3CrrE9WA"; address private openSeaProxyRegistryAddress = 0xa5409ec958C83C3f309868babACA7c86DCB077c1; bool private isOpenSeaProxyActive = true; uint256 public constant MAX_MINTS_PER_TX = 3; uint256 public maxSupply = 1000; uint256 public constant PUBLIC_SALE_PRICE = 0.05 ether; uint256 public NUM_FREE_MINTS = 200; bool public isPublicSaleActive = true; // ============ ACCESS CONTROL/SANITY MODIFIERS ============ modifier publicSaleActive() { require(isPublicSaleActive, "Public sale is not open"); _; } modifier maxMintsPerTX(uint256 numberOfTokens) { require( numberOfTokens <= MAX_MINTS_PER_TX, "Max mints per transaction exceeded" ); _; } modifier canMintNFTs(uint256 numberOfTokens) { require( tokenCounter.current() + numberOfTokens <= maxSupply, "Not enough mints remaining to mint" ); _; } modifier isCorrectPayment(uint256 price, uint256 numberOfTokens) { if(tokenCounter.current()>NUM_FREE_MINTS){ require( (price * numberOfTokens) <= msg.value, "Incorrect ETH value sent" ); } _; } constructor( ) ERC721("CryptoDungeons", "CryptoDungeons") { } // ============ PUBLIC FUNCTIONS FOR MINTING ============ function mint(uint256 numberOfTokens) external payable nonReentrant isCorrectPayment(PUBLIC_SALE_PRICE, numberOfTokens) publicSaleActive canMintNFTs(numberOfTokens) maxMintsPerTX(numberOfTokens) { for (uint256 i = 0; i < numberOfTokens; i++) { _safeMint(msg.sender, nextTokenId()); } } // ============ PUBLIC READ-ONLY FUNCTIONS ============ function getBaseURI() external view returns (string memory) { return baseURI; } function getLastTokenId() external view returns (uint256) { return tokenCounter.current(); } function totalSupply() external view returns (uint256) { return tokenCounter.current(); } // ============ OWNER-ONLY ADMIN FUNCTIONS ============ function setBaseURI(string memory _baseURI) external onlyOwner { baseURI = _baseURI; } // function to disable gasless listings for security in case // opensea ever shuts down or is compromised function setIsOpenSeaProxyActive(bool _isOpenSeaProxyActive) external onlyOwner { isOpenSeaProxyActive = _isOpenSeaProxyActive; } function setIsPublicSaleActive(bool _isPublicSaleActive) external onlyOwner { isPublicSaleActive = _isPublicSaleActive; } function setNumFreeMints(uint256 _numfreemints) external onlyOwner { NUM_FREE_MINTS = _numfreemints; } function withdraw() public onlyOwner { uint256 balance = address(this).balance; payable(msg.sender).transfer(balance); } function withdrawTokens(IERC20 token) public onlyOwner { uint256 balance = token.balanceOf(address(this)); token.transfer(msg.sender, balance); } // ============ SUPPORTING FUNCTIONS ============ function nextTokenId() private returns (uint256) { tokenCounter.increment(); return tokenCounter.current(); } // ============ FUNCTION OVERRIDES ============ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721, IERC165) returns (bool) { return interfaceId == type(IERC2981).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Override isApprovedForAll to allowlist user's OpenSea proxy accounts to enable gas-less listings. */ function isApprovedForAll(address owner, address operator) public view override returns (bool) { // Get a reference to OpenSea's proxy registry contract by instantiating // the contract using the already existing address. ProxyRegistry proxyRegistry = ProxyRegistry( openSeaProxyRegistryAddress ); if ( isOpenSeaProxyActive && address(proxyRegistry.proxies(owner)) == operator ) { return true; } return super.isApprovedForAll(owner, operator); } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "Nonexistent token"); return string(abi.encodePacked(baseURI, "/", tokenId.toString(), ".json")); } /** * @dev See {IERC165-royaltyInfo}. */ function royaltyInfo(uint256 tokenId, uint256 salePrice) external view override returns (address receiver, uint256 royaltyAmount) { require(_exists(tokenId), "Nonexistent token"); return (address(this), SafeMath.div(SafeMath.mul(salePrice, 10), 100)); } } // These contract definitions are used to create a reference to the OpenSea // ProxyRegistry contract by using the registry's address (see isApprovedForAll). contract OwnableDelegateProxy { } contract ProxyRegistry { mapping(address => OwnableDelegateProxy) public proxies; }
File: coven/vapes.solSPDX-License-Identifier: MITContract based on [https:docs.openzeppelin.com/contracts/3.x/erc721](https:docs.openzeppelin.com/contracts/3.x/erc721) ============ ACCESS CONTROL/SANITY MODIFIERS ============
contract CryptoDungeons is ERC721, IERC2981, Ownable, ReentrancyGuard { using Counters for Counters.Counter; using Strings for uint256; Counters.Counter private tokenCounter; address private openSeaProxyRegistryAddress = 0xa5409ec958C83C3f309868babACA7c86DCB077c1; bool private isOpenSeaProxyActive = true; uint256 public constant MAX_MINTS_PER_TX = 3; uint256 public maxSupply = 1000; uint256 public constant PUBLIC_SALE_PRICE = 0.05 ether; uint256 public NUM_FREE_MINTS = 200; bool public isPublicSaleActive = true; function _beforeTokenTransfer( address from, address to, uint256 tokenId } pragma solidity ^0.8.0; modifier publicSaleActive() { require(isPublicSaleActive, "Public sale is not open"); _; } modifier maxMintsPerTX(uint256 numberOfTokens) { require( numberOfTokens <= MAX_MINTS_PER_TX, "Max mints per transaction exceeded" ); _; } modifier canMintNFTs(uint256 numberOfTokens) { require( tokenCounter.current() + numberOfTokens <= maxSupply, "Not enough mints remaining to mint" ); _; } modifier isCorrectPayment(uint256 price, uint256 numberOfTokens) { if(tokenCounter.current()>NUM_FREE_MINTS){ require( (price * numberOfTokens) <= msg.value, "Incorrect ETH value sent" ); } _; } constructor( modifier isCorrectPayment(uint256 price, uint256 numberOfTokens) { if(tokenCounter.current()>NUM_FREE_MINTS){ require( (price * numberOfTokens) <= msg.value, "Incorrect ETH value sent" ); } _; } constructor( ) ERC721("CryptoDungeons", "CryptoDungeons") { } function mint(uint256 numberOfTokens) external payable nonReentrant isCorrectPayment(PUBLIC_SALE_PRICE, numberOfTokens) publicSaleActive canMintNFTs(numberOfTokens) maxMintsPerTX(numberOfTokens) { for (uint256 i = 0; i < numberOfTokens; i++) { _safeMint(msg.sender, nextTokenId()); } } function mint(uint256 numberOfTokens) external payable nonReentrant isCorrectPayment(PUBLIC_SALE_PRICE, numberOfTokens) publicSaleActive canMintNFTs(numberOfTokens) maxMintsPerTX(numberOfTokens) { for (uint256 i = 0; i < numberOfTokens; i++) { _safeMint(msg.sender, nextTokenId()); } } function getBaseURI() external view returns (string memory) { return baseURI; } function getLastTokenId() external view returns (uint256) { return tokenCounter.current(); } function totalSupply() external view returns (uint256) { return tokenCounter.current(); } function setBaseURI(string memory _baseURI) external onlyOwner { baseURI = _baseURI; } function setIsOpenSeaProxyActive(bool _isOpenSeaProxyActive) external onlyOwner { isOpenSeaProxyActive = _isOpenSeaProxyActive; } function setIsPublicSaleActive(bool _isPublicSaleActive) external onlyOwner { isPublicSaleActive = _isPublicSaleActive; } function setNumFreeMints(uint256 _numfreemints) external onlyOwner { NUM_FREE_MINTS = _numfreemints; } function withdraw() public onlyOwner { uint256 balance = address(this).balance; payable(msg.sender).transfer(balance); } function withdrawTokens(IERC20 token) public onlyOwner { uint256 balance = token.balanceOf(address(this)); token.transfer(msg.sender, balance); } function nextTokenId() private returns (uint256) { tokenCounter.increment(); return tokenCounter.current(); } function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721, IERC165) returns (bool) { return interfaceId == type(IERC2981).interfaceId || super.supportsInterface(interfaceId); } function isApprovedForAll(address owner, address operator) public view override returns (bool) { ProxyRegistry proxyRegistry = ProxyRegistry( openSeaProxyRegistryAddress ); if ( isOpenSeaProxyActive && address(proxyRegistry.proxies(owner)) == operator ) { return true; } return super.isApprovedForAll(owner, operator); } function isApprovedForAll(address owner, address operator) public view override returns (bool) { ProxyRegistry proxyRegistry = ProxyRegistry( openSeaProxyRegistryAddress ); if ( isOpenSeaProxyActive && address(proxyRegistry.proxies(owner)) == operator ) { return true; } return super.isApprovedForAll(owner, operator); } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "Nonexistent token"); return string(abi.encodePacked(baseURI, "/", tokenId.toString(), ".json")); } function royaltyInfo(uint256 tokenId, uint256 salePrice) external view override returns (address receiver, uint256 royaltyAmount) { require(_exists(tokenId), "Nonexistent token"); return (address(this), SafeMath.div(SafeMath.mul(salePrice, 10), 100)); } }
15,225,342
[ 1, 812, 30, 10613, 275, 19, 90, 7315, 18, 18281, 3118, 28826, 17, 13211, 17, 3004, 30, 490, 1285, 8924, 2511, 603, 306, 4528, 30, 8532, 18, 3190, 94, 881, 84, 292, 267, 18, 832, 19, 16351, 87, 19, 23, 18, 92, 19, 12610, 27, 5340, 29955, 4528, 30, 8532, 18, 3190, 94, 881, 84, 292, 267, 18, 832, 19, 16351, 87, 19, 23, 18, 92, 19, 12610, 27, 5340, 13, 422, 1432, 631, 13255, 8020, 13429, 19, 22721, 4107, 8663, 10591, 55, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 16351, 15629, 40, 25561, 7008, 353, 4232, 39, 27, 5340, 16, 467, 654, 39, 5540, 11861, 16, 14223, 6914, 16, 868, 8230, 12514, 16709, 288, 203, 565, 1450, 9354, 87, 364, 9354, 87, 18, 4789, 31, 203, 565, 1450, 8139, 364, 2254, 5034, 31, 203, 203, 565, 9354, 87, 18, 4789, 3238, 1147, 4789, 31, 203, 203, 565, 1758, 3238, 1696, 1761, 69, 3886, 4243, 1887, 273, 374, 6995, 6564, 5908, 557, 29, 8204, 39, 10261, 39, 23, 74, 5082, 29, 5292, 28, 70, 378, 2226, 37, 27, 71, 5292, 5528, 38, 20, 4700, 71, 21, 31, 203, 565, 1426, 3238, 16633, 1761, 69, 3886, 3896, 273, 638, 31, 203, 203, 565, 2254, 5034, 1071, 5381, 4552, 67, 49, 3217, 55, 67, 3194, 67, 16556, 273, 890, 31, 203, 565, 2254, 5034, 1071, 943, 3088, 1283, 273, 4336, 31, 203, 203, 565, 2254, 5034, 1071, 5381, 17187, 67, 5233, 900, 67, 7698, 1441, 273, 374, 18, 6260, 225, 2437, 31, 203, 565, 2254, 5034, 1071, 9443, 67, 28104, 67, 49, 3217, 55, 273, 4044, 31, 203, 565, 1426, 1071, 19620, 30746, 3896, 273, 638, 31, 203, 203, 203, 203, 203, 203, 565, 445, 389, 5771, 1345, 5912, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 1147, 548, 203, 97, 203, 203, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 20, 31, 203, 203, 203, 203, 203, 203, 203, 203, 203, 203, 565, 9606, 1071, 30746, 3896, 1435, 288, 203, 3639, 2583, 12, 291, 4782, 2 ]
pragma solidity ^0.5.16; import "./ComptrollerInterface.sol"; import "./CTokenInterfaces.sol"; import "./ErrorReporter.sol"; import "./Exponential.sol"; import "./EIP20Interface.sol"; import "./EIP20NonStandardInterface.sol"; import "./InterestRateModel.sol"; /** * @title Compound's CToken Contract * @notice Abstract base for CTokens * @author Compound */ contract CToken is CTokenInterface, Exponential, TokenErrorReporter { /** * @notice Initialize the money market * @param comptroller_ The address of the Comptroller * @param interestRateModel_ The address of the interest rate model * @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18 * @param name_ EIP-20 name of this token * @param symbol_ EIP-20 symbol of this token * @param decimals_ EIP-20 decimal precision of this token */ function initialize( ComptrollerInterface comptroller_, InterestRateModel interestRateModel_, uint256 initialExchangeRateMantissa_, string memory name_, string memory symbol_, uint8 decimals_ ) public { require(msg.sender == admin, "only admin may initialize the market"); require(accrualBlockNumber == 0 && borrowIndex == 0, "market may only be initialized once"); // Set initial exchange rate initialExchangeRateMantissa = initialExchangeRateMantissa_; require(initialExchangeRateMantissa > 0, "initial exchange rate must be greater than zero."); // Set the comptroller uint256 err = _setComptroller(comptroller_); require(err == uint256(Error.NO_ERROR), "setting comptroller failed"); // Initialize block number and borrow index (block number mocks depend on comptroller being set) accrualBlockNumber = getBlockNumber(); borrowIndex = mantissaOne; // Set the interest rate model (depends on block number / borrow index) err = _setInterestRateModelFresh(interestRateModel_); require(err == uint256(Error.NO_ERROR), "setting interest rate model failed"); name = name_; symbol = symbol_; decimals = decimals_; // The counter starts true to prevent changing it from zero to non-zero (i.e. smaller cost/refund) _notEntered = true; } /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint256 amount) external nonReentrant returns (bool) { return transferTokens(msg.sender, msg.sender, dst, amount) == uint256(Error.NO_ERROR); } /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom( address src, address dst, uint256 amount ) external nonReentrant returns (bool) { return transferTokens(msg.sender, src, dst, amount) == uint256(Error.NO_ERROR); } /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved (-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint256 amount) external returns (bool) { address src = msg.sender; transferAllowances[src][spender] = amount; emit Approval(src, spender, amount); return true; } /** * @notice Get the current allowance from `owner` for `spender` * @param owner The address of the account which owns the tokens to be spent * @param spender The address of the account which may transfer tokens * @return The number of tokens allowed to be spent (-1 means infinite) */ function allowance(address owner, address spender) external view returns (uint256) { return transferAllowances[owner][spender]; } /** * @notice Get the token balance of the `owner` * @param owner The address of the account to query * @return The number of tokens owned by `owner` */ function balanceOf(address owner) external view returns (uint256) { return accountTokens[owner]; } /** * @notice Get the underlying balance of the `owner` * @dev This also accrues interest in a transaction * @param owner The address of the account to query * @return The amount of underlying owned by `owner` */ function balanceOfUnderlying(address owner) external returns (uint256) { Exp memory exchangeRate = Exp({mantissa: exchangeRateCurrent()}); return mul_ScalarTruncate(exchangeRate, accountTokens[owner]); } /** * @notice Get a snapshot of the account's balances, and the cached exchange rate * @dev This is used by comptroller to more efficiently perform liquidity checks. * @param account Address of the account to snapshot * @return (possible error, token balance, borrow balance, exchange rate mantissa) */ function getAccountSnapshot(address account) external view returns ( uint256, uint256, uint256, uint256 ) { uint256 cTokenBalance = getCTokenBalanceInternal(account); uint256 borrowBalance = borrowBalanceStoredInternal(account); uint256 exchangeRateMantissa = exchangeRateStoredInternal(); return (uint256(Error.NO_ERROR), cTokenBalance, borrowBalance, exchangeRateMantissa); } /** * @dev Function to simply retrieve block number * This exists mainly for inheriting test contracts to stub this result. */ function getBlockNumber() internal view returns (uint256) { return block.number; } /** * @notice Returns the current per-block borrow interest rate for this cToken * @return The borrow interest rate per block, scaled by 1e18 */ function borrowRatePerBlock() external view returns (uint256) { return interestRateModel.getBorrowRate(getCashPrior(), totalBorrows, totalReserves); } /** * @notice Returns the current per-block supply interest rate for this cToken * @return The supply interest rate per block, scaled by 1e18 */ function supplyRatePerBlock() external view returns (uint256) { return interestRateModel.getSupplyRate(getCashPrior(), totalBorrows, totalReserves, reserveFactorMantissa); } /** * @notice Returns the estimated per-block borrow interest rate for this cToken after some change * @return The borrow interest rate per block, scaled by 1e18 */ function estimateBorrowRatePerBlockAfterChange(uint256 change, bool repay) external view returns (uint256) { uint256 cashPriorNew; uint256 totalBorrowsNew; if (repay) { cashPriorNew = add_(getCashPrior(), change); totalBorrowsNew = sub_(totalBorrows, change); } else { cashPriorNew = sub_(getCashPrior(), change); totalBorrowsNew = add_(totalBorrows, change); } return interestRateModel.getBorrowRate(cashPriorNew, totalBorrowsNew, totalReserves); } /** * @notice Returns the estimated per-block supply interest rate for this cToken after some change * @return The supply interest rate per block, scaled by 1e18 */ function estimateSupplyRatePerBlockAfterChange(uint256 change, bool repay) external view returns (uint256) { uint256 cashPriorNew; uint256 totalBorrowsNew; if (repay) { cashPriorNew = add_(getCashPrior(), change); totalBorrowsNew = sub_(totalBorrows, change); } else { cashPriorNew = sub_(getCashPrior(), change); totalBorrowsNew = add_(totalBorrows, change); } return interestRateModel.getSupplyRate(cashPriorNew, totalBorrowsNew, totalReserves, reserveFactorMantissa); } /** * @notice Returns the current total borrows plus accrued interest * @return The total borrows with interest */ function totalBorrowsCurrent() external nonReentrant returns (uint256) { require(accrueInterest() == uint256(Error.NO_ERROR), "accrue interest failed"); return totalBorrows; } /** * @notice Accrue interest to updated borrowIndex and then calculate account's borrow balance using the updated borrowIndex * @param account The address whose balance should be calculated after updating borrowIndex * @return The calculated balance */ function borrowBalanceCurrent(address account) external nonReentrant returns (uint256) { require(accrueInterest() == uint256(Error.NO_ERROR), "accrue interest failed"); return borrowBalanceStored(account); } /** * @notice Return the borrow balance of account based on stored data * @param account The address whose balance should be calculated * @return The calculated balance */ function borrowBalanceStored(address account) public view returns (uint256) { return borrowBalanceStoredInternal(account); } /** * @notice Return the borrow balance of account based on stored data * @param account The address whose balance should be calculated * @return the calculated balance or 0 if error code is non-zero */ function borrowBalanceStoredInternal(address account) internal view returns (uint256) { /* Get borrowBalance and borrowIndex */ BorrowSnapshot storage borrowSnapshot = accountBorrows[account]; /* If borrowBalance = 0 then borrowIndex is likely also 0. * Rather than failing the calculation with a division by 0, we immediately return 0 in this case. */ if (borrowSnapshot.principal == 0) { return 0; } /* Calculate new borrow balance using the interest index: * recentBorrowBalance = borrower.borrowBalance * market.borrowIndex / borrower.borrowIndex */ uint256 principalTimesIndex = mul_(borrowSnapshot.principal, borrowIndex); uint256 result = div_(principalTimesIndex, borrowSnapshot.interestIndex); return result; } /** * @notice Accrue interest then return the up-to-date exchange rate * @return Calculated exchange rate scaled by 1e18 */ function exchangeRateCurrent() public nonReentrant returns (uint256) { require(accrueInterest() == uint256(Error.NO_ERROR), "accrue interest failed"); return exchangeRateStored(); } /** * @notice Calculates the exchange rate from the underlying to the CToken * @dev This function does not accrue interest before calculating the exchange rate * @return Calculated exchange rate scaled by 1e18 */ function exchangeRateStored() public view returns (uint256) { return exchangeRateStoredInternal(); } /** * @notice Calculates the exchange rate from the underlying to the CToken * @dev This function does not accrue interest before calculating the exchange rate * @return calculated exchange rate scaled by 1e18 */ function exchangeRateStoredInternal() internal view returns (uint256) { uint256 _totalSupply = totalSupply; if (_totalSupply == 0) { /* * If there are no tokens minted: * exchangeRate = initialExchangeRate */ return initialExchangeRateMantissa; } else { /* * Otherwise: * exchangeRate = (totalCash + totalBorrows - totalReserves) / totalSupply */ uint256 totalCash = getCashPrior(); uint256 cashPlusBorrowsMinusReserves = sub_(add_(totalCash, totalBorrows), totalReserves); uint256 exchangeRate = div_(cashPlusBorrowsMinusReserves, Exp({mantissa: _totalSupply})); return exchangeRate; } } /** * @notice Get cash balance of this cToken in the underlying asset * @return The quantity of underlying asset owned by this contract */ function getCash() external view returns (uint256) { return getCashPrior(); } /** * @notice Applies accrued interest to total borrows and reserves * @dev This calculates interest accrued from the last checkpointed block * up to the current block and writes new checkpoint to storage. */ function accrueInterest() public returns (uint256) { /* Remember the initial block number */ uint256 currentBlockNumber = getBlockNumber(); uint256 accrualBlockNumberPrior = accrualBlockNumber; /* Short-circuit accumulating 0 interest */ if (accrualBlockNumberPrior == currentBlockNumber) { return uint256(Error.NO_ERROR); } /* Read the previous values out of storage */ uint256 cashPrior = getCashPrior(); uint256 borrowsPrior = totalBorrows; uint256 reservesPrior = totalReserves; uint256 borrowIndexPrior = borrowIndex; /* Calculate the current borrow interest rate */ uint256 borrowRateMantissa = interestRateModel.getBorrowRate(cashPrior, borrowsPrior, reservesPrior); require(borrowRateMantissa <= borrowRateMaxMantissa, "borrow rate is absurdly high"); /* Calculate the number of blocks elapsed since the last accrual */ uint256 blockDelta = sub_(currentBlockNumber, accrualBlockNumberPrior); /* * Calculate the interest accumulated into borrows and reserves and the new index: * simpleInterestFactor = borrowRate * blockDelta * interestAccumulated = simpleInterestFactor * totalBorrows * totalBorrowsNew = interestAccumulated + totalBorrows * totalReservesNew = interestAccumulated * reserveFactor + totalReserves * borrowIndexNew = simpleInterestFactor * borrowIndex + borrowIndex */ Exp memory simpleInterestFactor = mul_(Exp({mantissa: borrowRateMantissa}), blockDelta); uint256 interestAccumulated = mul_ScalarTruncate(simpleInterestFactor, borrowsPrior); uint256 totalBorrowsNew = add_(interestAccumulated, borrowsPrior); uint256 totalReservesNew = mul_ScalarTruncateAddUInt( Exp({mantissa: reserveFactorMantissa}), interestAccumulated, reservesPrior ); uint256 borrowIndexNew = mul_ScalarTruncateAddUInt(simpleInterestFactor, borrowIndexPrior, borrowIndexPrior); ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* We write the previously calculated values into storage */ accrualBlockNumber = currentBlockNumber; borrowIndex = borrowIndexNew; totalBorrows = totalBorrowsNew; totalReserves = totalReservesNew; /* We emit an AccrueInterest event */ emit AccrueInterest(cashPrior, interestAccumulated, borrowIndexNew, totalBorrowsNew); return uint256(Error.NO_ERROR); } /** * @notice Sender supplies assets into the market and receives cTokens in exchange * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param mintAmount The amount of the underlying asset to supply * @param isNative The amount is in native or not * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount. */ function mintInternal(uint256 mintAmount, bool isNative) internal nonReentrant returns (uint256, uint256) { uint256 error = accrueInterest(); if (error != uint256(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed return (fail(Error(error), FailureInfo.MINT_ACCRUE_INTEREST_FAILED), 0); } // mintFresh emits the actual Mint event if successful and logs on errors, so we don't need to return mintFresh(msg.sender, mintAmount, isNative); } /** * @notice Sender redeems cTokens in exchange for the underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemTokens The number of cTokens to redeem into underlying * @param isNative The amount is in native or not * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemInternal(uint256 redeemTokens, bool isNative) internal nonReentrant returns (uint256) { uint256 error = accrueInterest(); if (error != uint256(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED); } // redeemFresh emits redeem-specific logs on errors, so we don't need to return redeemFresh(msg.sender, redeemTokens, 0, isNative); } /** * @notice Sender redeems cTokens in exchange for a specified amount of underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemAmount The amount of underlying to receive from redeeming cTokens * @param isNative The amount is in native or not * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemUnderlyingInternal(uint256 redeemAmount, bool isNative) internal nonReentrant returns (uint256) { uint256 error = accrueInterest(); if (error != uint256(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED); } // redeemFresh emits redeem-specific logs on errors, so we don't need to return redeemFresh(msg.sender, 0, redeemAmount, isNative); } /** * @notice Sender borrows assets from the protocol to their own address * @param borrowAmount The amount of the underlying asset to borrow * @param isNative The amount is in native or not * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrowInternal(uint256 borrowAmount, bool isNative) internal nonReentrant returns (uint256) { uint256 error = accrueInterest(); if (error != uint256(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed return fail(Error(error), FailureInfo.BORROW_ACCRUE_INTEREST_FAILED); } // borrowFresh emits borrow-specific logs on errors, so we don't need to return borrowFresh(msg.sender, borrowAmount, isNative); } struct BorrowLocalVars { MathError mathErr; uint256 accountBorrows; uint256 accountBorrowsNew; uint256 totalBorrowsNew; } /** * @notice Users borrow assets from the protocol to their own address * @param borrowAmount The amount of the underlying asset to borrow * @param isNative The amount is in native or not * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrowFresh( address payable borrower, uint256 borrowAmount, bool isNative ) internal returns (uint256) { /* Fail if borrow not allowed */ uint256 allowed = comptroller.borrowAllowed(address(this), borrower, borrowAmount); if (allowed != 0) { return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.BORROW_COMPTROLLER_REJECTION, allowed); } /* * Return if borrowAmount is zero. * Put behind `borrowAllowed` for accuring potential COMP rewards. */ if (borrowAmount == 0) { accountBorrows[borrower].interestIndex = borrowIndex; return uint256(Error.NO_ERROR); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.BORROW_FRESHNESS_CHECK); } /* Fail gracefully if protocol has insufficient underlying cash */ if (getCashPrior() < borrowAmount) { return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.BORROW_CASH_NOT_AVAILABLE); } BorrowLocalVars memory vars; /* * We calculate the new borrower and total borrow balances, failing on overflow: * accountBorrowsNew = accountBorrows + borrowAmount * totalBorrowsNew = totalBorrows + borrowAmount */ vars.accountBorrows = borrowBalanceStoredInternal(borrower); vars.accountBorrowsNew = add_(vars.accountBorrows, borrowAmount); vars.totalBorrowsNew = add_(totalBorrows, borrowAmount); ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* We write the previously calculated values into storage */ accountBorrows[borrower].principal = vars.accountBorrowsNew; accountBorrows[borrower].interestIndex = borrowIndex; totalBorrows = vars.totalBorrowsNew; /* * We invoke doTransferOut for the borrower and the borrowAmount. * Note: The cToken must handle variations between ERC-20 and ETH underlying. * On success, the cToken borrowAmount less of cash. * doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred. */ doTransferOut(borrower, borrowAmount, isNative); /* We emit a Borrow event */ emit Borrow(borrower, borrowAmount, vars.accountBorrowsNew, vars.totalBorrowsNew); /* We call the defense hook */ comptroller.borrowVerify(address(this), borrower, borrowAmount); return uint256(Error.NO_ERROR); } /** * @notice Sender repays their own borrow * @param repayAmount The amount to repay * @param isNative The amount is in native or not * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function repayBorrowInternal(uint256 repayAmount, bool isNative) internal nonReentrant returns (uint256, uint256) { uint256 error = accrueInterest(); if (error != uint256(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed return (fail(Error(error), FailureInfo.REPAY_BORROW_ACCRUE_INTEREST_FAILED), 0); } // repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to return repayBorrowFresh(msg.sender, msg.sender, repayAmount, isNative); } /** * @notice Sender repays a borrow belonging to borrower * @param borrower the account with the debt being payed off * @param repayAmount The amount to repay * @param isNative The amount is in native or not * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function repayBorrowBehalfInternal( address borrower, uint256 repayAmount, bool isNative ) internal nonReentrant returns (uint256, uint256) { uint256 error = accrueInterest(); if (error != uint256(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed return (fail(Error(error), FailureInfo.REPAY_BEHALF_ACCRUE_INTEREST_FAILED), 0); } // repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to return repayBorrowFresh(msg.sender, borrower, repayAmount, isNative); } struct RepayBorrowLocalVars { Error err; MathError mathErr; uint256 repayAmount; uint256 borrowerIndex; uint256 accountBorrows; uint256 accountBorrowsNew; uint256 totalBorrowsNew; uint256 actualRepayAmount; } /** * @notice Borrows are repaid by another user (possibly the borrower). * @param payer the account paying off the borrow * @param borrower the account with the debt being payed off * @param repayAmount the amount of undelrying tokens being returned * @param isNative The amount is in native or not * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function repayBorrowFresh( address payer, address borrower, uint256 repayAmount, bool isNative ) internal returns (uint256, uint256) { /* Fail if repayBorrow not allowed */ uint256 allowed = comptroller.repayBorrowAllowed(address(this), payer, borrower, repayAmount); if (allowed != 0) { return ( failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.REPAY_BORROW_COMPTROLLER_REJECTION, allowed), 0 ); } /* * Return if repayAmount is zero. * Put behind `repayBorrowAllowed` for accuring potential COMP rewards. */ if (repayAmount == 0) { accountBorrows[borrower].interestIndex = borrowIndex; return (uint256(Error.NO_ERROR), 0); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.REPAY_BORROW_FRESHNESS_CHECK), 0); } RepayBorrowLocalVars memory vars; /* We remember the original borrowerIndex for verification purposes */ vars.borrowerIndex = accountBorrows[borrower].interestIndex; /* We fetch the amount the borrower owes, with accumulated interest */ vars.accountBorrows = borrowBalanceStoredInternal(borrower); /* If repayAmount == -1, repayAmount = accountBorrows */ if (repayAmount == uint256(-1)) { vars.repayAmount = vars.accountBorrows; } else { vars.repayAmount = repayAmount; } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We call doTransferIn for the payer and the repayAmount * Note: The cToken must handle variations between ERC-20 and ETH underlying. * On success, the cToken holds an additional repayAmount of cash. * doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred. * it returns the amount actually transferred, in case of a fee. */ vars.actualRepayAmount = doTransferIn(payer, vars.repayAmount, isNative); /* * We calculate the new borrower and total borrow balances, failing on underflow: * accountBorrowsNew = accountBorrows - actualRepayAmount * totalBorrowsNew = totalBorrows - actualRepayAmount */ vars.accountBorrowsNew = sub_(vars.accountBorrows, vars.actualRepayAmount); vars.totalBorrowsNew = sub_(totalBorrows, vars.actualRepayAmount); /* We write the previously calculated values into storage */ accountBorrows[borrower].principal = vars.accountBorrowsNew; accountBorrows[borrower].interestIndex = borrowIndex; totalBorrows = vars.totalBorrowsNew; /* We emit a RepayBorrow event */ emit RepayBorrow(payer, borrower, vars.actualRepayAmount, vars.accountBorrowsNew, vars.totalBorrowsNew); /* We call the defense hook */ comptroller.repayBorrowVerify(address(this), payer, borrower, vars.actualRepayAmount, vars.borrowerIndex); return (uint256(Error.NO_ERROR), vars.actualRepayAmount); } /** * @notice The sender liquidates the borrowers collateral. * The collateral seized is transferred to the liquidator. * @param borrower The borrower of this cToken to be liquidated * @param repayAmount The amount of the underlying borrowed asset to repay * @param cTokenCollateral The market in which to seize collateral from the borrower * @param isNative The amount is in native or not * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function liquidateBorrowInternal( address borrower, uint256 repayAmount, CTokenInterface cTokenCollateral, bool isNative ) internal nonReentrant returns (uint256, uint256) { uint256 error = accrueInterest(); if (error != uint256(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED), 0); } error = cTokenCollateral.accrueInterest(); if (error != uint256(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED), 0); } // liquidateBorrowFresh emits borrow-specific logs on errors, so we don't need to return liquidateBorrowFresh(msg.sender, borrower, repayAmount, cTokenCollateral, isNative); } struct LiquidateBorrowLocalVars { uint256 repayBorrowError; uint256 actualRepayAmount; uint256 amountSeizeError; uint256 seizeTokens; } /** * @notice The liquidator liquidates the borrowers collateral. * The collateral seized is transferred to the liquidator. * @param borrower The borrower of this cToken to be liquidated * @param liquidator The address repaying the borrow and seizing collateral * @param cTokenCollateral The market in which to seize collateral from the borrower * @param repayAmount The amount of the underlying borrowed asset to repay * @param isNative The amount is in native or not * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function liquidateBorrowFresh( address liquidator, address borrower, uint256 repayAmount, CTokenInterface cTokenCollateral, bool isNative ) internal returns (uint256, uint256) { /* Fail if liquidate not allowed */ uint256 allowed = comptroller.liquidateBorrowAllowed( address(this), address(cTokenCollateral), liquidator, borrower, repayAmount ); if (allowed != 0) { return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.LIQUIDATE_COMPTROLLER_REJECTION, allowed), 0); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_FRESHNESS_CHECK), 0); } /* Verify cTokenCollateral market's block number equals current block number */ if (cTokenCollateral.accrualBlockNumber() != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_COLLATERAL_FRESHNESS_CHECK), 0); } /* Fail if borrower = liquidator */ if (borrower == liquidator) { return (fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_LIQUIDATOR_IS_BORROWER), 0); } /* Fail if repayAmount = 0 */ if (repayAmount == 0) { return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_ZERO), 0); } /* Fail if repayAmount = -1 */ if (repayAmount == uint256(-1)) { return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX), 0); } LiquidateBorrowLocalVars memory vars; /* Fail if repayBorrow fails */ (vars.repayBorrowError, vars.actualRepayAmount) = repayBorrowFresh(liquidator, borrower, repayAmount, isNative); if (vars.repayBorrowError != uint256(Error.NO_ERROR)) { return (fail(Error(vars.repayBorrowError), FailureInfo.LIQUIDATE_REPAY_BORROW_FRESH_FAILED), 0); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* We calculate the number of collateral tokens that will be seized */ (vars.amountSeizeError, vars.seizeTokens) = comptroller.liquidateCalculateSeizeTokens( address(this), address(cTokenCollateral), vars.actualRepayAmount ); require( vars.amountSeizeError == uint256(Error.NO_ERROR), "LIQUIDATE_COMPTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED" ); /* Revert if borrower collateral token balance < seizeTokens */ require(cTokenCollateral.balanceOf(borrower) >= vars.seizeTokens, "LIQUIDATE_SEIZE_TOO_MUCH"); // If this is also the collateral, run seizeInternal to avoid re-entrancy, otherwise make an external call uint256 seizeError; if (address(cTokenCollateral) == address(this)) { seizeError = seizeInternal(address(this), liquidator, borrower, vars.seizeTokens); } else { seizeError = cTokenCollateral.seize(liquidator, borrower, vars.seizeTokens); } /* Revert if seize tokens fails (since we cannot be sure of side effects) */ require(seizeError == uint256(Error.NO_ERROR), "token seizure failed"); /* We emit a LiquidateBorrow event */ emit LiquidateBorrow(liquidator, borrower, vars.actualRepayAmount, address(cTokenCollateral), vars.seizeTokens); /* We call the defense hook */ comptroller.liquidateBorrowVerify( address(this), address(cTokenCollateral), liquidator, borrower, vars.actualRepayAmount, vars.seizeTokens ); return (uint256(Error.NO_ERROR), vars.actualRepayAmount); } /** * @notice Transfers collateral tokens (this market) to the liquidator. * @dev Will fail unless called by another cToken during the process of liquidation. * Its absolutely critical to use msg.sender as the borrowed cToken and not a parameter. * @param liquidator The account receiving seized collateral * @param borrower The account having collateral seized * @param seizeTokens The number of cTokens to seize * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function seize( address liquidator, address borrower, uint256 seizeTokens ) external nonReentrant returns (uint256) { return seizeInternal(msg.sender, liquidator, borrower, seizeTokens); } /*** Admin Functions ***/ /** * @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @param newPendingAdmin New pending admin. * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setPendingAdmin(address payable newPendingAdmin) external returns (uint256) { // Check caller = admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK); } // Save current value, if any, for inclusion in log address oldPendingAdmin = pendingAdmin; // Store pendingAdmin with value newPendingAdmin pendingAdmin = newPendingAdmin; // Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin) emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin); return uint256(Error.NO_ERROR); } /** * @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin * @dev Admin function for pending admin to accept role and update admin * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _acceptAdmin() external returns (uint256) { // Check caller is pendingAdmin and pendingAdmin ≠ address(0) if (msg.sender != pendingAdmin || msg.sender == address(0)) { return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_ADMIN_PENDING_ADMIN_CHECK); } // Save current values for inclusion in log address oldAdmin = admin; address oldPendingAdmin = pendingAdmin; // Store admin with value pendingAdmin admin = pendingAdmin; // Clear the pending value pendingAdmin = address(0); emit NewAdmin(oldAdmin, admin); emit NewPendingAdmin(oldPendingAdmin, pendingAdmin); return uint256(Error.NO_ERROR); } /** * @notice Sets a new comptroller for the market * @dev Admin function to set a new comptroller * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setComptroller(ComptrollerInterface newComptroller) public returns (uint256) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_COMPTROLLER_OWNER_CHECK); } ComptrollerInterface oldComptroller = comptroller; // Ensure invoke comptroller.isComptroller() returns true require(newComptroller.isComptroller(), "marker method returned false"); // Set market's comptroller to newComptroller comptroller = newComptroller; // Emit NewComptroller(oldComptroller, newComptroller) emit NewComptroller(oldComptroller, newComptroller); return uint256(Error.NO_ERROR); } /** * @notice accrues interest and sets a new reserve factor for the protocol using _setReserveFactorFresh * @dev Admin function to accrue interest and set a new reserve factor * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setReserveFactor(uint256 newReserveFactorMantissa) external nonReentrant returns (uint256) { uint256 error = accrueInterest(); if (error != uint256(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reserve factor change failed. return fail(Error(error), FailureInfo.SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED); } // _setReserveFactorFresh emits reserve-factor-specific logs on errors, so we don't need to. return _setReserveFactorFresh(newReserveFactorMantissa); } /** * @notice Sets a new reserve factor for the protocol (*requires fresh interest accrual) * @dev Admin function to set a new reserve factor * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setReserveFactorFresh(uint256 newReserveFactorMantissa) internal returns (uint256) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_RESERVE_FACTOR_ADMIN_CHECK); } // Verify market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_RESERVE_FACTOR_FRESH_CHECK); } // Check newReserveFactor ≤ maxReserveFactor if (newReserveFactorMantissa > reserveFactorMaxMantissa) { return fail(Error.BAD_INPUT, FailureInfo.SET_RESERVE_FACTOR_BOUNDS_CHECK); } uint256 oldReserveFactorMantissa = reserveFactorMantissa; reserveFactorMantissa = newReserveFactorMantissa; emit NewReserveFactor(oldReserveFactorMantissa, newReserveFactorMantissa); return uint256(Error.NO_ERROR); } /** * @notice Accrues interest and reduces reserves by transferring from msg.sender * @param addAmount Amount of addition to reserves * @param isNative The amount is in native or not * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _addReservesInternal(uint256 addAmount, bool isNative) internal nonReentrant returns (uint256) { uint256 error = accrueInterest(); if (error != uint256(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed. return fail(Error(error), FailureInfo.ADD_RESERVES_ACCRUE_INTEREST_FAILED); } // _addReservesFresh emits reserve-addition-specific logs on errors, so we don't need to. (error, ) = _addReservesFresh(addAmount, isNative); return error; } /** * @notice Add reserves by transferring from caller * @dev Requires fresh interest accrual * @param addAmount Amount of addition to reserves * @param isNative The amount is in native or not * @return (uint, uint) An error code (0=success, otherwise a failure (see ErrorReporter.sol for details)) and the actual amount added, net token fees */ function _addReservesFresh(uint256 addAmount, bool isNative) internal returns (uint256, uint256) { // totalReserves + actualAddAmount uint256 totalReservesNew; uint256 actualAddAmount; // We fail gracefully unless market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.ADD_RESERVES_FRESH_CHECK), actualAddAmount); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We call doTransferIn for the caller and the addAmount * Note: The cToken must handle variations between ERC-20 and ETH underlying. * On success, the cToken holds an additional addAmount of cash. * doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred. * it returns the amount actually transferred, in case of a fee. */ actualAddAmount = doTransferIn(msg.sender, addAmount, isNative); totalReservesNew = add_(totalReserves, actualAddAmount); // Store reserves[n+1] = reserves[n] + actualAddAmount totalReserves = totalReservesNew; /* Emit NewReserves(admin, actualAddAmount, reserves[n+1]) */ emit ReservesAdded(msg.sender, actualAddAmount, totalReservesNew); /* Return (NO_ERROR, actualAddAmount) */ return (uint256(Error.NO_ERROR), actualAddAmount); } /** * @notice Accrues interest and reduces reserves by transferring to admin * @param reduceAmount Amount of reduction to reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _reduceReserves(uint256 reduceAmount) external nonReentrant returns (uint256) { uint256 error = accrueInterest(); if (error != uint256(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed. return fail(Error(error), FailureInfo.REDUCE_RESERVES_ACCRUE_INTEREST_FAILED); } // _reduceReservesFresh emits reserve-reduction-specific logs on errors, so we don't need to. return _reduceReservesFresh(reduceAmount); } /** * @notice Reduces reserves by transferring to admin * @dev Requires fresh interest accrual * @param reduceAmount Amount of reduction to reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _reduceReservesFresh(uint256 reduceAmount) internal returns (uint256) { // totalReserves - reduceAmount uint256 totalReservesNew; // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.REDUCE_RESERVES_ADMIN_CHECK); } // We fail gracefully unless market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDUCE_RESERVES_FRESH_CHECK); } // Fail gracefully if protocol has insufficient underlying cash if (getCashPrior() < reduceAmount) { return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDUCE_RESERVES_CASH_NOT_AVAILABLE); } // Check reduceAmount ≤ reserves[n] (totalReserves) if (reduceAmount > totalReserves) { return fail(Error.BAD_INPUT, FailureInfo.REDUCE_RESERVES_VALIDATION); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) totalReservesNew = sub_(totalReserves, reduceAmount); // Store reserves[n+1] = reserves[n] - reduceAmount totalReserves = totalReservesNew; // doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred. // Restrict reducing reserves in native token. Implementations except `CWrappedNative` won't use parameter `isNative`. doTransferOut(admin, reduceAmount, true); emit ReservesReduced(admin, reduceAmount, totalReservesNew); return uint256(Error.NO_ERROR); } /** * @notice accrues interest and updates the interest rate model using _setInterestRateModelFresh * @dev Admin function to accrue interest and update the interest rate model * @param newInterestRateModel the new interest rate model to use * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint256) { uint256 error = accrueInterest(); if (error != uint256(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted change of interest rate model failed return fail(Error(error), FailureInfo.SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED); } // _setInterestRateModelFresh emits interest-rate-model-update-specific logs on errors, so we don't need to. return _setInterestRateModelFresh(newInterestRateModel); } /** * @notice updates the interest rate model (*requires fresh interest accrual) * @dev Admin function to update the interest rate model * @param newInterestRateModel the new interest rate model to use * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setInterestRateModelFresh(InterestRateModel newInterestRateModel) internal returns (uint256) { // Used to store old model for use in the event that is emitted on success InterestRateModel oldInterestRateModel; // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_INTEREST_RATE_MODEL_OWNER_CHECK); } // We fail gracefully unless market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_INTEREST_RATE_MODEL_FRESH_CHECK); } // Track the market's current interest rate model oldInterestRateModel = interestRateModel; // Ensure invoke newInterestRateModel.isInterestRateModel() returns true require(newInterestRateModel.isInterestRateModel(), "marker method returned false"); // Set the interest rate model to newInterestRateModel interestRateModel = newInterestRateModel; // Emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel) emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel); return uint256(Error.NO_ERROR); } /*** Safe Token ***/ /** * @notice Gets balance of this contract in terms of the underlying * @dev This excludes the value of the current message, if any * @return The quantity of underlying owned by this contract */ function getCashPrior() internal view returns (uint256); /** * @dev Performs a transfer in, reverting upon failure. Returns the amount actually transferred to the protocol, in case of a fee. * This may revert due to insufficient balance or insufficient allowance. */ function doTransferIn( address from, uint256 amount, bool isNative ) internal returns (uint256); /** * @dev Performs a transfer out, ideally returning an explanatory error code upon failure tather than reverting. * If caller has not called checked protocol's balance, may revert due to insufficient cash held in the contract. * If caller has checked protocol's balance, and verified it is >= amount, this should not revert in normal conditions. */ function doTransferOut( address payable to, uint256 amount, bool isNative ) internal; /** * @notice Transfer `tokens` tokens from `src` to `dst` by `spender` * @dev Called by both `transfer` and `transferFrom` internally */ function transferTokens( address spender, address src, address dst, uint256 tokens ) internal returns (uint256); /** * @notice Get the account's cToken balances */ function getCTokenBalanceInternal(address account) internal view returns (uint256); /** * @notice User supplies assets into the market and receives cTokens in exchange * @dev Assumes interest has already been accrued up to the current block */ function mintFresh( address minter, uint256 mintAmount, bool isNative ) internal returns (uint256, uint256); /** * @notice User redeems cTokens in exchange for the underlying asset * @dev Assumes interest has already been accrued up to the current block */ function redeemFresh( address payable redeemer, uint256 redeemTokensIn, uint256 redeemAmountIn, bool isNative ) internal returns (uint256); /** * @notice Transfers collateral tokens (this market) to the liquidator. * @dev Called only during an in-kind liquidation, or by liquidateBorrow during the liquidation of another CToken. * Its absolutely critical to use msg.sender as the seizer cToken and not a parameter. */ function seizeInternal( address seizerToken, address liquidator, address borrower, uint256 seizeTokens ) internal returns (uint256); /*** Reentrancy Guard ***/ /** * @dev Prevents a contract from calling itself, directly or indirectly. */ modifier nonReentrant() { require(_notEntered, "re-entered"); _notEntered = false; _; _notEntered = true; // get a gas-refund post-Istanbul } } pragma solidity ^0.5.16; import "./ComptrollerInterface.sol"; import "./InterestRateModel.sol"; import "./ERC3156FlashBorrowerInterface.sol"; contract CTokenStorage { /** * @dev Guard variable for re-entrancy checks */ bool internal _notEntered; /** * @notice EIP-20 token name for this token */ string public name; /** * @notice EIP-20 token symbol for this token */ string public symbol; /** * @notice EIP-20 token decimals for this token */ uint8 public decimals; /** * @notice Maximum borrow rate that can ever be applied (.0005% / block) */ uint256 internal constant borrowRateMaxMantissa = 0.0005e16; /** * @notice Maximum fraction of interest that can be set aside for reserves */ uint256 internal constant reserveFactorMaxMantissa = 1e18; /** * @notice Administrator for this contract */ address payable public admin; /** * @notice Pending administrator for this contract */ address payable public pendingAdmin; /** * @notice Contract which oversees inter-cToken operations */ ComptrollerInterface public comptroller; /** * @notice Model which tells what the current interest rate should be */ InterestRateModel public interestRateModel; /** * @notice Initial exchange rate used when minting the first CTokens (used when totalSupply = 0) */ uint256 internal initialExchangeRateMantissa; /** * @notice Fraction of interest currently set aside for reserves */ uint256 public reserveFactorMantissa; /** * @notice Block number that interest was last accrued at */ uint256 public accrualBlockNumber; /** * @notice Accumulator of the total earned interest rate since the opening of the market */ uint256 public borrowIndex; /** * @notice Total amount of outstanding borrows of the underlying in this market */ uint256 public totalBorrows; /** * @notice Total amount of reserves of the underlying held in this market */ uint256 public totalReserves; /** * @notice Total number of tokens in circulation */ uint256 public totalSupply; /** * @notice Official record of token balances for each account */ mapping(address => uint256) internal accountTokens; /** * @notice Approved token transfer amounts on behalf of others */ mapping(address => mapping(address => uint256)) internal transferAllowances; /** * @notice Container for borrow balance information * @member principal Total balance (with accrued interest), after applying the most recent balance-changing action * @member interestIndex Global borrowIndex as of the most recent balance-changing action */ struct BorrowSnapshot { uint256 principal; uint256 interestIndex; } /** * @notice Mapping of account addresses to outstanding borrow balances */ mapping(address => BorrowSnapshot) internal accountBorrows; } contract CErc20Storage { /** * @notice Underlying asset for this CToken */ address public underlying; /** * @notice Implementation address for this contract */ address public implementation; } contract CSupplyCapStorage { /** * @notice Internal cash counter for this CToken. Should equal underlying.balanceOf(address(this)) for CERC20. */ uint256 public internalCash; } contract CCollateralCapStorage { /** * @notice Total number of tokens used as collateral in circulation. */ uint256 public totalCollateralTokens; /** * @notice Record of token balances which could be treated as collateral for each account. * If collateral cap is not set, the value should be equal to accountTokens. */ mapping(address => uint256) public accountCollateralTokens; /** * @notice Check if accountCollateralTokens have been initialized. */ mapping(address => bool) public isCollateralTokenInit; /** * @notice Collateral cap for this CToken, zero for no cap. */ uint256 public collateralCap; } /*** Interface ***/ contract CTokenInterface is CTokenStorage { /** * @notice Indicator that this is a CToken contract (for inspection) */ bool public constant isCToken = true; /*** Market Events ***/ /** * @notice Event emitted when interest is accrued */ event AccrueInterest(uint256 cashPrior, uint256 interestAccumulated, uint256 borrowIndex, uint256 totalBorrows); /** * @notice Event emitted when tokens are minted */ event Mint(address minter, uint256 mintAmount, uint256 mintTokens); /** * @notice Event emitted when tokens are redeemed */ event Redeem(address redeemer, uint256 redeemAmount, uint256 redeemTokens); /** * @notice Event emitted when underlying is borrowed */ event Borrow(address borrower, uint256 borrowAmount, uint256 accountBorrows, uint256 totalBorrows); /** * @notice Event emitted when a borrow is repaid */ event RepayBorrow( address payer, address borrower, uint256 repayAmount, uint256 accountBorrows, uint256 totalBorrows ); /** * @notice Event emitted when a borrow is liquidated */ event LiquidateBorrow( address liquidator, address borrower, uint256 repayAmount, address cTokenCollateral, uint256 seizeTokens ); /*** Admin Events ***/ /** * @notice Event emitted when pendingAdmin is changed */ event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin); /** * @notice Event emitted when pendingAdmin is accepted, which means admin is updated */ event NewAdmin(address oldAdmin, address newAdmin); /** * @notice Event emitted when comptroller is changed */ event NewComptroller(ComptrollerInterface oldComptroller, ComptrollerInterface newComptroller); /** * @notice Event emitted when interestRateModel is changed */ event NewMarketInterestRateModel(InterestRateModel oldInterestRateModel, InterestRateModel newInterestRateModel); /** * @notice Event emitted when the reserve factor is changed */ event NewReserveFactor(uint256 oldReserveFactorMantissa, uint256 newReserveFactorMantissa); /** * @notice Event emitted when the reserves are added */ event ReservesAdded(address benefactor, uint256 addAmount, uint256 newTotalReserves); /** * @notice Event emitted when the reserves are reduced */ event ReservesReduced(address admin, uint256 reduceAmount, uint256 newTotalReserves); /** * @notice EIP20 Transfer event */ event Transfer(address indexed from, address indexed to, uint256 amount); /** * @notice EIP20 Approval event */ event Approval(address indexed owner, address indexed spender, uint256 amount); /** * @notice Failure event */ event Failure(uint256 error, uint256 info, uint256 detail); /*** User Interface ***/ function transfer(address dst, uint256 amount) external returns (bool); function transferFrom( address src, address dst, 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 balanceOf(address owner) external view returns (uint256); function balanceOfUnderlying(address owner) external returns (uint256); function getAccountSnapshot(address account) external view returns ( uint256, uint256, uint256, uint256 ); function borrowRatePerBlock() external view returns (uint256); function supplyRatePerBlock() external view returns (uint256); function totalBorrowsCurrent() external returns (uint256); function borrowBalanceCurrent(address account) external returns (uint256); function borrowBalanceStored(address account) public view returns (uint256); function exchangeRateCurrent() public returns (uint256); function exchangeRateStored() public view returns (uint256); function getCash() external view returns (uint256); function accrueInterest() public returns (uint256); function seize( address liquidator, address borrower, uint256 seizeTokens ) external returns (uint256); /*** Admin Functions ***/ function _setPendingAdmin(address payable newPendingAdmin) external returns (uint256); function _acceptAdmin() external returns (uint256); function _setComptroller(ComptrollerInterface newComptroller) public returns (uint256); function _setReserveFactor(uint256 newReserveFactorMantissa) external returns (uint256); function _reduceReserves(uint256 reduceAmount) external returns (uint256); function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint256); } contract CErc20Interface is CErc20Storage { /*** User Interface ***/ function mint(uint256 mintAmount) external returns (uint256); function redeem(uint256 redeemTokens) external returns (uint256); function redeemUnderlying(uint256 redeemAmount) external returns (uint256); function borrow(uint256 borrowAmount) external returns (uint256); function repayBorrow(uint256 repayAmount) external returns (uint256); function repayBorrowBehalf(address borrower, uint256 repayAmount) external returns (uint256); function liquidateBorrow( address borrower, uint256 repayAmount, CTokenInterface cTokenCollateral ) external returns (uint256); function _addReserves(uint256 addAmount) external returns (uint256); } contract CWrappedNativeInterface is CErc20Interface { /** * @notice Flash loan fee ratio */ uint256 public constant flashFeeBips = 3; /*** Market Events ***/ /** * @notice Event emitted when a flashloan occured */ event Flashloan(address indexed receiver, uint256 amount, uint256 totalFee, uint256 reservesFee); /*** User Interface ***/ function mintNative() external payable returns (uint256); function redeemNative(uint256 redeemTokens) external returns (uint256); function redeemUnderlyingNative(uint256 redeemAmount) external returns (uint256); function borrowNative(uint256 borrowAmount) external returns (uint256); function repayBorrowNative() external payable returns (uint256); function repayBorrowBehalfNative(address borrower) external payable returns (uint256); function liquidateBorrowNative(address borrower, CTokenInterface cTokenCollateral) external payable returns (uint256); function flashLoan( ERC3156FlashBorrowerInterface receiver, address initiator, uint256 amount, bytes calldata data ) external returns (bool); function _addReservesNative() external payable returns (uint256); } contract CCapableErc20Interface is CErc20Interface, CSupplyCapStorage { /** * @notice Flash loan fee ratio */ uint256 public constant flashFeeBips = 3; /*** Market Events ***/ /** * @notice Event emitted when a flashloan occured */ event Flashloan(address indexed receiver, uint256 amount, uint256 totalFee, uint256 reservesFee); /*** User Interface ***/ function gulp() external; } contract CCollateralCapErc20Interface is CCapableErc20Interface, CCollateralCapStorage { /*** Admin Events ***/ /** * @notice Event emitted when collateral cap is set */ event NewCollateralCap(address token, uint256 newCap); /** * @notice Event emitted when user collateral is changed */ event UserCollateralChanged(address account, uint256 newCollateralTokens); /*** User Interface ***/ function registerCollateral(address account) external returns (uint256); function unregisterCollateral(address account) external; function flashLoan( ERC3156FlashBorrowerInterface receiver, address initiator, uint256 amount, bytes calldata data ) external returns (bool); /*** Admin Functions ***/ function _setCollateralCap(uint256 newCollateralCap) external; } contract CDelegatorInterface { /** * @notice Emitted when implementation is changed */ event NewImplementation(address oldImplementation, address newImplementation); /** * @notice Called by the admin to update the implementation of the delegator * @param implementation_ The address of the new implementation for delegation * @param allowResign Flag to indicate whether to call _resignImplementation on the old implementation * @param becomeImplementationData The encoded bytes data to be passed to _becomeImplementation */ function _setImplementation( address implementation_, bool allowResign, bytes memory becomeImplementationData ) public; } contract CDelegateInterface { /** * @notice Called by the delegator on a delegate to initialize it for duty * @dev Should revert if any issues arise which make it unfit for delegation * @param data The encoded bytes data for any initialization */ function _becomeImplementation(bytes memory data) public; /** * @notice Called by the delegator on a delegate to forfeit its responsibility */ function _resignImplementation() public; } /*** External interface ***/ /** * @title Flash loan receiver interface */ interface IFlashloanReceiver { function executeOperation( address sender, address underlying, uint256 amount, uint256 fee, bytes calldata params ) external; } pragma solidity ^0.5.16; /** * @title Careful Math * @author Compound * @notice Derived from OpenZeppelin's SafeMath library * https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/math/SafeMath.sol */ contract CarefulMath { /** * @dev Possible error codes that we can return */ enum MathError { NO_ERROR, DIVISION_BY_ZERO, INTEGER_OVERFLOW, INTEGER_UNDERFLOW } /** * @dev Multiplies two numbers, returns an error on overflow. */ function mulUInt(uint256 a, uint256 b) internal pure returns (MathError, uint256) { if (a == 0) { return (MathError.NO_ERROR, 0); } uint256 c = a * b; if (c / a != b) { return (MathError.INTEGER_OVERFLOW, 0); } else { return (MathError.NO_ERROR, c); } } /** * @dev Integer division of two numbers, truncating the quotient. */ function divUInt(uint256 a, uint256 b) internal pure returns (MathError, uint256) { if (b == 0) { return (MathError.DIVISION_BY_ZERO, 0); } return (MathError.NO_ERROR, a / b); } /** * @dev Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend). */ function subUInt(uint256 a, uint256 b) internal pure returns (MathError, uint256) { if (b <= a) { return (MathError.NO_ERROR, a - b); } else { return (MathError.INTEGER_UNDERFLOW, 0); } } /** * @dev Adds two numbers, returns an error on overflow. */ function addUInt(uint256 a, uint256 b) internal pure returns (MathError, uint256) { uint256 c = a + b; if (c >= a) { return (MathError.NO_ERROR, c); } else { return (MathError.INTEGER_OVERFLOW, 0); } } /** * @dev add a and b and then subtract c */ function addThenSubUInt( uint256 a, uint256 b, uint256 c ) internal pure returns (MathError, uint256) { (MathError err0, uint256 sum) = addUInt(a, b); if (err0 != MathError.NO_ERROR) { return (err0, 0); } return subUInt(sum, c); } } pragma solidity ^0.5.16; import "./CToken.sol"; import "./ErrorReporter.sol"; import "./Exponential.sol"; import "./PriceOracle/PriceOracle.sol"; import "./ComptrollerInterface.sol"; import "./ComptrollerStorage.sol"; import "./LiquidityMiningInterface.sol"; import "./Unitroller.sol"; import "./Governance/Comp.sol"; /** * @title Compound's Comptroller Contract * @author Compound (modified by Cream) */ contract Comptroller is ComptrollerV7Storage, ComptrollerInterface, ComptrollerErrorReporter, Exponential { /// @notice Emitted when an admin supports a market event MarketListed(CToken cToken); /// @notice Emitted when an admin delists a market event MarketDelisted(CToken cToken); /// @notice Emitted when an account enters a market event MarketEntered(CToken cToken, address account); /// @notice Emitted when an account exits a market event MarketExited(CToken cToken, address account); /// @notice Emitted when close factor is changed by admin event NewCloseFactor(uint256 oldCloseFactorMantissa, uint256 newCloseFactorMantissa); /// @notice Emitted when a collateral factor is changed by admin event NewCollateralFactor(CToken cToken, uint256 oldCollateralFactorMantissa, uint256 newCollateralFactorMantissa); /// @notice Emitted when liquidation incentive is changed by admin event NewLiquidationIncentive(uint256 oldLiquidationIncentiveMantissa, uint256 newLiquidationIncentiveMantissa); /// @notice Emitted when price oracle is changed event NewPriceOracle(PriceOracle oldPriceOracle, PriceOracle newPriceOracle); /// @notice Emitted when pause guardian is changed event NewPauseGuardian(address oldPauseGuardian, address newPauseGuardian); /// @notice Emitted when liquidity mining module is changed event NewLiquidityMining(address oldLiquidityMining, address newLiquidityMining); /// @notice Emitted when an action is paused globally event ActionPaused(string action, bool pauseState); /// @notice Emitted when an action is paused on a market event ActionPaused(CToken cToken, string action, bool pauseState); /// @notice Emitted when COMP is distributed to a supplier event DistributedSupplierComp( CToken indexed cToken, address indexed supplier, uint256 compDelta, uint256 compSupplyIndex ); /// @notice Emitted when COMP is distributed to a borrower event DistributedBorrowerComp( CToken indexed cToken, address indexed borrower, uint256 compDelta, uint256 compBorrowIndex ); /// @notice Emitted when borrow cap for a cToken is changed event NewBorrowCap(CToken indexed cToken, uint256 newBorrowCap); /// @notice Emitted when borrow cap guardian is changed event NewBorrowCapGuardian(address oldBorrowCapGuardian, address newBorrowCapGuardian); /// @notice Emitted when supply cap for a cToken is changed event NewSupplyCap(CToken indexed cToken, uint256 newSupplyCap); /// @notice Emitted when supply cap guardian is changed event NewSupplyCapGuardian(address oldSupplyCapGuardian, address newSupplyCapGuardian); /// @notice Emitted when cToken version is changed event NewCTokenVersion(CToken cToken, Version oldVersion, Version newVersion); /// @notice The initial COMP index for a market uint224 public constant compInitialIndex = 1e36; // No collateralFactorMantissa may exceed this value uint256 internal constant collateralFactorMaxMantissa = 0.9e18; // 0.9 constructor() public { admin = msg.sender; } /*** Assets You Are In ***/ /** * @notice Returns the assets an account has entered * @param account The address of the account to pull assets for * @return A dynamic list with the assets the account has entered */ function getAssetsIn(address account) external view returns (CToken[] memory) { CToken[] memory assetsIn = accountAssets[account]; return assetsIn; } /** * @notice Returns whether the given account is entered in the given asset * @param account The address of the account to check * @param cToken The cToken to check * @return True if the account is in the asset, otherwise false. */ function checkMembership(address account, CToken cToken) external view returns (bool) { return markets[address(cToken)].accountMembership[account]; } /** * @notice Add assets to be included in account liquidity calculation * @param cTokens The list of addresses of the cToken markets to be enabled * @return Success indicator for whether each corresponding market was entered */ function enterMarkets(address[] memory cTokens) public returns (uint256[] memory) { uint256 len = cTokens.length; uint256[] memory results = new uint256[](len); for (uint256 i = 0; i < len; i++) { CToken cToken = CToken(cTokens[i]); results[i] = uint256(addToMarketInternal(cToken, msg.sender)); } return results; } /** * @notice Add the market to the borrower's "assets in" for liquidity calculations * @param cToken The market to enter * @param borrower The address of the account to modify * @return Success indicator for whether the market was entered */ function addToMarketInternal(CToken cToken, address borrower) internal returns (Error) { Market storage marketToJoin = markets[address(cToken)]; if (!marketToJoin.isListed) { // market is not listed, cannot join return Error.MARKET_NOT_LISTED; } if (marketToJoin.version == Version.COLLATERALCAP) { // register collateral for the borrower if the token is CollateralCap version. CCollateralCapErc20Interface(address(cToken)).registerCollateral(borrower); } if (marketToJoin.accountMembership[borrower] == true) { // already joined return Error.NO_ERROR; } // survived the gauntlet, add to list // NOTE: we store these somewhat redundantly as a significant optimization // this avoids having to iterate through the list for the most common use cases // that is, only when we need to perform liquidity checks // and not whenever we want to check if an account is in a particular market marketToJoin.accountMembership[borrower] = true; accountAssets[borrower].push(cToken); emit MarketEntered(cToken, borrower); return Error.NO_ERROR; } /** * @notice Removes asset from sender's account liquidity calculation * @dev Sender must not have an outstanding borrow balance in the asset, * or be providing necessary collateral for an outstanding borrow. * @param cTokenAddress The address of the asset to be removed * @return Whether or not the account successfully exited the market */ function exitMarket(address cTokenAddress) external returns (uint256) { CToken cToken = CToken(cTokenAddress); /* Get sender tokensHeld and amountOwed underlying from the cToken */ (uint256 oErr, uint256 tokensHeld, uint256 amountOwed, ) = cToken.getAccountSnapshot(msg.sender); require(oErr == 0, "exitMarket: getAccountSnapshot failed"); // semi-opaque error code /* Fail if the sender has a borrow balance */ if (amountOwed != 0) { return fail(Error.NONZERO_BORROW_BALANCE, FailureInfo.EXIT_MARKET_BALANCE_OWED); } /* Fail if the sender is not permitted to redeem all of their tokens */ uint256 allowed = redeemAllowedInternal(cTokenAddress, msg.sender, tokensHeld); if (allowed != 0) { return failOpaque(Error.REJECTION, FailureInfo.EXIT_MARKET_REJECTION, allowed); } Market storage marketToExit = markets[cTokenAddress]; if (marketToExit.version == Version.COLLATERALCAP) { CCollateralCapErc20Interface(cTokenAddress).unregisterCollateral(msg.sender); } /* Return true if the sender is not already ‘in’ the market */ if (!marketToExit.accountMembership[msg.sender]) { return uint256(Error.NO_ERROR); } /* Set cToken account membership to false */ delete marketToExit.accountMembership[msg.sender]; /* Delete cToken from the account’s list of assets */ // load into memory for faster iteration CToken[] memory userAssetList = accountAssets[msg.sender]; uint256 len = userAssetList.length; uint256 assetIndex = len; for (uint256 i = 0; i < len; i++) { if (userAssetList[i] == cToken) { assetIndex = i; break; } } // We *must* have found the asset in the list or our redundant data structure is broken assert(assetIndex < len); // copy last item in list to location of item to be removed, reduce length by 1 CToken[] storage storedList = accountAssets[msg.sender]; if (assetIndex != storedList.length - 1) { storedList[assetIndex] = storedList[storedList.length - 1]; } storedList.length--; emit MarketExited(cToken, msg.sender); return uint256(Error.NO_ERROR); } /** * @notice Return a specific market is listed or not * @param cTokenAddress The address of the asset to be checked * @return Whether or not the market is listed */ function isMarketListed(address cTokenAddress) public view returns (bool) { return markets[cTokenAddress].isListed; } /*** Policy Hooks ***/ /** * @notice Checks if the account should be allowed to mint tokens in the given market * @param cToken The market to verify the mint against * @param minter The account which would get the minted tokens * @param mintAmount The amount of underlying being supplied to the market in exchange for tokens * @return 0 if the mint is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function mintAllowed( address cToken, address minter, uint256 mintAmount ) external returns (uint256) { // Pausing is a very serious situation - we revert to sound the alarms require(!mintGuardianPaused[cToken], "mint is paused"); // Shh - currently unused minter; if (!isMarketListed(cToken)) { return uint256(Error.MARKET_NOT_LISTED); } uint256 supplyCap = supplyCaps[cToken]; // Supply cap of 0 corresponds to unlimited supplying if (supplyCap != 0) { uint256 totalCash = CToken(cToken).getCash(); uint256 totalBorrows = CToken(cToken).totalBorrows(); uint256 totalReserves = CToken(cToken).totalReserves(); // totalSupplies = totalCash + totalBorrows - totalReserves (MathError mathErr, uint256 totalSupplies) = addThenSubUInt(totalCash, totalBorrows, totalReserves); require(mathErr == MathError.NO_ERROR, "totalSupplies failed"); uint256 nextTotalSupplies = add_(totalSupplies, mintAmount); require(nextTotalSupplies < supplyCap, "market supply cap reached"); } return uint256(Error.NO_ERROR); } /** * @notice Validates mint and reverts on rejection. May emit logs. * @param cToken Asset being minted * @param minter The address minting the tokens * @param actualMintAmount The amount of the underlying asset being minted * @param mintTokens The number of tokens being minted */ function mintVerify( address cToken, address minter, uint256 actualMintAmount, uint256 mintTokens ) external { // Shh - currently unused cToken; minter; actualMintAmount; mintTokens; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /** * @notice Checks if the account should be allowed to redeem tokens in the given market * @param cToken The market to verify the redeem against * @param redeemer The account which would redeem the tokens * @param redeemTokens The number of cTokens to exchange for the underlying asset in the market * @return 0 if the redeem is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function redeemAllowed( address cToken, address redeemer, uint256 redeemTokens ) external returns (uint256) { return redeemAllowedInternal(cToken, redeemer, redeemTokens); } function redeemAllowedInternal( address cToken, address redeemer, uint256 redeemTokens ) internal view returns (uint256) { // cToken: crEth if (cToken == 0xD06527D5e56A3495252A528C4987003b712860eE && redeemer == 0xf701426b8126BC60530574CEcDCb365D47973284) { revert("redeemer is blacklisted"); } if (!isMarketListed(cToken)) { return uint256(Error.MARKET_NOT_LISTED); } /* If the redeemer is not 'in' the market, then we can bypass the liquidity check */ if (!markets[cToken].accountMembership[redeemer]) { return uint256(Error.NO_ERROR); } /* Otherwise, perform a hypothetical liquidity check to guard against shortfall */ (Error err, , uint256 shortfall) = getHypotheticalAccountLiquidityInternal( redeemer, CToken(cToken), redeemTokens, 0 ); if (err != Error.NO_ERROR) { return uint256(err); } if (shortfall > 0) { return uint256(Error.INSUFFICIENT_LIQUIDITY); } return uint256(Error.NO_ERROR); } /** * @notice Validates redeem and reverts on rejection. May emit logs. * @param cToken Asset being redeemed * @param redeemer The address redeeming the tokens * @param redeemAmount The amount of the underlying asset being redeemed * @param redeemTokens The number of tokens being redeemed */ function redeemVerify( address cToken, address redeemer, uint256 redeemAmount, uint256 redeemTokens ) external { // Shh - currently unused cToken; redeemer; // Require tokens is zero or amount is also zero if (redeemTokens == 0 && redeemAmount > 0) { revert("redeemTokens zero"); } } /** * @notice Checks if the account should be allowed to borrow the underlying asset of the given market * @param cToken The market to verify the borrow against * @param borrower The account which would borrow the asset * @param borrowAmount The amount of underlying the account would borrow * @return 0 if the borrow is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function borrowAllowed( address cToken, address borrower, uint256 borrowAmount ) external returns (uint256) { // Pausing is a very serious situation - we revert to sound the alarms require(!borrowGuardianPaused[cToken], "borrow is paused"); if (borrower == 0xf701426b8126BC60530574CEcDCb365D47973284) { revert("borrower is blacklisted"); } if (!isMarketListed(cToken)) { return uint256(Error.MARKET_NOT_LISTED); } if (!markets[cToken].accountMembership[borrower]) { // only cTokens may call borrowAllowed if borrower not in market require(msg.sender == cToken, "sender must be cToken"); // attempt to add borrower to the market Error err = addToMarketInternal(CToken(msg.sender), borrower); if (err != Error.NO_ERROR) { return uint256(err); } // it should be impossible to break the important invariant assert(markets[cToken].accountMembership[borrower]); } if (oracle.getUnderlyingPrice(CToken(cToken)) == 0) { return uint256(Error.PRICE_ERROR); } uint256 borrowCap = borrowCaps[cToken]; // Borrow cap of 0 corresponds to unlimited borrowing if (borrowCap != 0) { uint256 totalBorrows = CToken(cToken).totalBorrows(); uint256 nextTotalBorrows = add_(totalBorrows, borrowAmount); require(nextTotalBorrows < borrowCap, "market borrow cap reached"); } (Error err, , uint256 shortfall) = getHypotheticalAccountLiquidityInternal( borrower, CToken(cToken), 0, borrowAmount ); if (err != Error.NO_ERROR) { return uint256(err); } if (shortfall > 0) { return uint256(Error.INSUFFICIENT_LIQUIDITY); } return uint256(Error.NO_ERROR); } /** * @notice Validates borrow and reverts on rejection. May emit logs. * @param cToken Asset whose underlying is being borrowed * @param borrower The address borrowing the underlying * @param borrowAmount The amount of the underlying asset requested to borrow */ function borrowVerify( address cToken, address borrower, uint256 borrowAmount ) external { // Shh - currently unused cToken; borrower; borrowAmount; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /** * @notice Checks if the account should be allowed to repay a borrow in the given market * @param cToken The market to verify the repay against * @param payer The account which would repay the asset * @param borrower The account which would borrowed the asset * @param repayAmount The amount of the underlying asset the account would repay * @return 0 if the repay is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function repayBorrowAllowed( address cToken, address payer, address borrower, uint256 repayAmount ) external returns (uint256) { // Shh - currently unused payer; borrower; repayAmount; if (borrower == 0xf701426b8126BC60530574CEcDCb365D47973284) { revert("cannot repay for blacklist"); } if (!isMarketListed(cToken)) { return uint256(Error.MARKET_NOT_LISTED); } return uint256(Error.NO_ERROR); } /** * @notice Validates repayBorrow and reverts on rejection. May emit logs. * @param cToken Asset being repaid * @param payer The address repaying the borrow * @param borrower The address of the borrower * @param actualRepayAmount The amount of underlying being repaid */ function repayBorrowVerify( address cToken, address payer, address borrower, uint256 actualRepayAmount, uint256 borrowerIndex ) external { // Shh - currently unused cToken; payer; borrower; actualRepayAmount; borrowerIndex; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /** * @notice Checks if the liquidation should be allowed to occur * @param cTokenBorrowed Asset which was borrowed by the borrower * @param cTokenCollateral Asset which was used as collateral and will be seized * @param liquidator The address repaying the borrow and seizing the collateral * @param borrower The address of the borrower * @param repayAmount The amount of underlying being repaid */ function liquidateBorrowAllowed( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint256 repayAmount ) external returns (uint256) { // Shh - currently unused liquidator; // cTokenCollateral: crEth if (cTokenCollateral == 0xD06527D5e56A3495252A528C4987003b712860eE && borrower == 0xf701426b8126BC60530574CEcDCb365D47973284) { revert("cannot seize from blacklist"); } if (!isMarketListed(cTokenBorrowed) || !isMarketListed(cTokenCollateral)) { return uint256(Error.MARKET_NOT_LISTED); } /* The borrower must have shortfall in order to be liquidatable */ (Error err, , uint256 shortfall) = getAccountLiquidityInternal(borrower); if (err != Error.NO_ERROR) { return uint256(err); } if (shortfall == 0) { return uint256(Error.INSUFFICIENT_SHORTFALL); } /* The liquidator may not repay more than what is allowed by the closeFactor */ uint256 borrowBalance = CToken(cTokenBorrowed).borrowBalanceStored(borrower); uint256 maxClose = mul_ScalarTruncate(Exp({mantissa: closeFactorMantissa}), borrowBalance); if (repayAmount > maxClose) { return uint256(Error.TOO_MUCH_REPAY); } return uint256(Error.NO_ERROR); } /** * @notice Validates liquidateBorrow and reverts on rejection. May emit logs. * @param cTokenBorrowed Asset which was borrowed by the borrower * @param cTokenCollateral Asset which was used as collateral and will be seized * @param liquidator The address repaying the borrow and seizing the collateral * @param borrower The address of the borrower * @param actualRepayAmount The amount of underlying being repaid */ function liquidateBorrowVerify( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint256 actualRepayAmount, uint256 seizeTokens ) external { // Shh - currently unused cTokenBorrowed; cTokenCollateral; liquidator; borrower; actualRepayAmount; seizeTokens; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /** * @notice Checks if the seizing of assets should be allowed to occur * @param cTokenCollateral Asset which was used as collateral and will be seized * @param cTokenBorrowed Asset which was borrowed by the borrower * @param liquidator The address repaying the borrow and seizing the collateral * @param borrower The address of the borrower * @param seizeTokens The number of collateral tokens to seize */ function seizeAllowed( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint256 seizeTokens ) external returns (uint256) { // Pausing is a very serious situation - we revert to sound the alarms require(!seizeGuardianPaused, "seize is paused"); // Shh - currently unused liquidator; seizeTokens; // cTokenCollateral: crEth if (cTokenCollateral == 0xD06527D5e56A3495252A528C4987003b712860eE && borrower == 0xf701426b8126BC60530574CEcDCb365D47973284) { revert("cannot seize from blacklist"); } if (!isMarketListed(cTokenCollateral) || !isMarketListed(cTokenBorrowed)) { return uint256(Error.MARKET_NOT_LISTED); } if (CToken(cTokenCollateral).comptroller() != CToken(cTokenBorrowed).comptroller()) { return uint256(Error.COMPTROLLER_MISMATCH); } return uint256(Error.NO_ERROR); } /** * @notice Validates seize and reverts on rejection. May emit logs. * @param cTokenCollateral Asset which was used as collateral and will be seized * @param cTokenBorrowed Asset which was borrowed by the borrower * @param liquidator The address repaying the borrow and seizing the collateral * @param borrower The address of the borrower * @param seizeTokens The number of collateral tokens to seize */ function seizeVerify( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint256 seizeTokens ) external { // Shh - currently unused cTokenCollateral; cTokenBorrowed; liquidator; borrower; seizeTokens; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /** * @notice Checks if the account should be allowed to transfer tokens in the given market * @param cToken The market to verify the transfer against * @param src The account which sources the tokens * @param dst The account which receives the tokens * @param transferTokens The number of cTokens to transfer * @return 0 if the transfer is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function transferAllowed( address cToken, address src, address dst, uint256 transferTokens ) external returns (uint256) { // Pausing is a very serious situation - we revert to sound the alarms require(!transferGuardianPaused, "transfer is paused"); // Shh - currently unused dst; // Currently the only consideration is whether or not // the src is allowed to redeem this many tokens return redeemAllowedInternal(cToken, src, transferTokens); } /** * @notice Validates transfer and reverts on rejection. May emit logs. * @param cToken Asset being transferred * @param src The account which sources the tokens * @param dst The account which receives the tokens * @param transferTokens The number of cTokens to transfer */ function transferVerify( address cToken, address src, address dst, uint256 transferTokens ) external { // Shh - currently unused cToken; src; dst; transferTokens; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /** * @notice Checks if the account should be allowed to transfer tokens in the given market * @param cToken The market to verify the transfer against * @param receiver The account which receives the tokens * @param amount The amount of the tokens * @param params The other parameters */ function flashloanAllowed( address cToken, address receiver, uint256 amount, bytes calldata params ) external view returns (bool) { return !flashloanGuardianPaused[cToken]; } /** * @notice Update CToken's version. * @param cToken Version of the asset being updated * @param newVersion The new version */ function updateCTokenVersion(address cToken, Version newVersion) external { require(msg.sender == cToken, "only cToken could update its version"); // This function will be called when a new CToken implementation becomes active. // If a new CToken is newly created, this market is not listed yet. The version of // this market will be taken care of when calling `_supportMarket`. if (isMarketListed(cToken)) { Version oldVersion = markets[cToken].version; markets[cToken].version = newVersion; emit NewCTokenVersion(CToken(cToken), oldVersion, newVersion); } } /*** Liquidity/Liquidation Calculations ***/ /** * @dev Local vars for avoiding stack-depth limits in calculating account liquidity. * Note that `cTokenBalance` is the number of cTokens the account owns in the market, * whereas `borrowBalance` is the amount of underlying that the account has borrowed. */ struct AccountLiquidityLocalVars { uint256 sumCollateral; uint256 sumBorrowPlusEffects; uint256 cTokenBalance; uint256 borrowBalance; uint256 exchangeRateMantissa; uint256 oraclePriceMantissa; Exp collateralFactor; Exp exchangeRate; Exp oraclePrice; Exp tokensToDenom; } /** * @notice Determine the current account liquidity wrt collateral requirements * @return (possible error code (semi-opaque), account liquidity in excess of collateral requirements, * account shortfall below collateral requirements) */ function getAccountLiquidity(address account) public view returns ( uint256, uint256, uint256 ) { (Error err, uint256 liquidity, uint256 shortfall) = getHypotheticalAccountLiquidityInternal( account, CToken(0), 0, 0 ); return (uint256(err), liquidity, shortfall); } /** * @notice Determine the current account liquidity wrt collateral requirements * @return (possible error code, account liquidity in excess of collateral requirements, * account shortfall below collateral requirements) */ function getAccountLiquidityInternal(address account) internal view returns ( Error, uint256, uint256 ) { return getHypotheticalAccountLiquidityInternal(account, CToken(0), 0, 0); } /** * @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed * @param cTokenModify The market to hypothetically redeem/borrow in * @param account The account to determine liquidity for * @param redeemTokens The number of tokens to hypothetically redeem * @param borrowAmount The amount of underlying to hypothetically borrow * @return (possible error code (semi-opaque), hypothetical account liquidity in excess of collateral requirements, * hypothetical account shortfall below collateral requirements) */ function getHypotheticalAccountLiquidity( address account, address cTokenModify, uint256 redeemTokens, uint256 borrowAmount ) public view returns ( uint256, uint256, uint256 ) { (Error err, uint256 liquidity, uint256 shortfall) = getHypotheticalAccountLiquidityInternal( account, CToken(cTokenModify), redeemTokens, borrowAmount ); return (uint256(err), liquidity, shortfall); } /** * @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed * @param cTokenModify The market to hypothetically redeem/borrow in * @param account The account to determine liquidity for * @param redeemTokens The number of tokens to hypothetically redeem * @param borrowAmount The amount of underlying to hypothetically borrow * @dev Note that we calculate the exchangeRateStored for each collateral cToken using stored data, * without calculating accumulated interest. * @return (possible error code, hypothetical account liquidity in excess of collateral requirements, * hypothetical account shortfall below collateral requirements) */ function getHypotheticalAccountLiquidityInternal( address account, CToken cTokenModify, uint256 redeemTokens, uint256 borrowAmount ) internal view returns ( Error, uint256, uint256 ) { AccountLiquidityLocalVars memory vars; // Holds all our calculation results uint256 oErr; // For each asset the account is in CToken[] memory assets = accountAssets[account]; for (uint256 i = 0; i < assets.length; i++) { CToken asset = assets[i]; // Read the balances and exchange rate from the cToken (oErr, vars.cTokenBalance, vars.borrowBalance, vars.exchangeRateMantissa) = asset.getAccountSnapshot( account ); if (oErr != 0) { // semi-opaque error code, we assume NO_ERROR == 0 is invariant between upgrades return (Error.SNAPSHOT_ERROR, 0, 0); } // Unlike compound protocol, getUnderlyingPrice is relatively expensive because we use ChainLink as our primary price feed. // If user has no supply / borrow balance on this asset, and user is not redeeming / borrowing this asset, skip it. if (vars.cTokenBalance == 0 && vars.borrowBalance == 0 && asset != cTokenModify) { continue; } vars.collateralFactor = Exp({mantissa: markets[address(asset)].collateralFactorMantissa}); vars.exchangeRate = Exp({mantissa: vars.exchangeRateMantissa}); // Get the normalized price of the asset vars.oraclePriceMantissa = oracle.getUnderlyingPrice(asset); if (vars.oraclePriceMantissa == 0) { return (Error.PRICE_ERROR, 0, 0); } vars.oraclePrice = Exp({mantissa: vars.oraclePriceMantissa}); // Pre-compute a conversion factor from tokens -> ether (normalized price value) vars.tokensToDenom = mul_(mul_(vars.collateralFactor, vars.exchangeRate), vars.oraclePrice); // sumCollateral += tokensToDenom * cTokenBalance vars.sumCollateral = mul_ScalarTruncateAddUInt(vars.tokensToDenom, vars.cTokenBalance, vars.sumCollateral); // sumBorrowPlusEffects += oraclePrice * borrowBalance vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt( vars.oraclePrice, vars.borrowBalance, vars.sumBorrowPlusEffects ); // Calculate effects of interacting with cTokenModify if (asset == cTokenModify) { // redeem effect // sumBorrowPlusEffects += tokensToDenom * redeemTokens vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt( vars.tokensToDenom, redeemTokens, vars.sumBorrowPlusEffects ); // borrow effect // sumBorrowPlusEffects += oraclePrice * borrowAmount vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt( vars.oraclePrice, borrowAmount, vars.sumBorrowPlusEffects ); } } // These are safe, as the underflow condition is checked first if (vars.sumCollateral > vars.sumBorrowPlusEffects) { return (Error.NO_ERROR, vars.sumCollateral - vars.sumBorrowPlusEffects, 0); } else { return (Error.NO_ERROR, 0, vars.sumBorrowPlusEffects - vars.sumCollateral); } } /** * @notice Calculate number of tokens of collateral asset to seize given an underlying amount * @dev Used in liquidation (called in cToken.liquidateBorrowFresh) * @param cTokenBorrowed The address of the borrowed cToken * @param cTokenCollateral The address of the collateral cToken * @param actualRepayAmount The amount of cTokenBorrowed underlying to convert into cTokenCollateral tokens * @return (errorCode, number of cTokenCollateral tokens to be seized in a liquidation) */ function liquidateCalculateSeizeTokens( address cTokenBorrowed, address cTokenCollateral, uint256 actualRepayAmount ) external view returns (uint256, uint256) { /* Read oracle prices for borrowed and collateral markets */ uint256 priceBorrowedMantissa = oracle.getUnderlyingPrice(CToken(cTokenBorrowed)); uint256 priceCollateralMantissa = oracle.getUnderlyingPrice(CToken(cTokenCollateral)); if (priceBorrowedMantissa == 0 || priceCollateralMantissa == 0) { return (uint256(Error.PRICE_ERROR), 0); } /* * Get the exchange rate and calculate the number of collateral tokens to seize: * seizeAmount = actualRepayAmount * liquidationIncentive * priceBorrowed / priceCollateral * seizeTokens = seizeAmount / exchangeRate * = actualRepayAmount * (liquidationIncentive * priceBorrowed) / (priceCollateral * exchangeRate) */ uint256 exchangeRateMantissa = CToken(cTokenCollateral).exchangeRateStored(); // Note: reverts on error Exp memory numerator = mul_( Exp({mantissa: liquidationIncentiveMantissa}), Exp({mantissa: priceBorrowedMantissa}) ); Exp memory denominator = mul_(Exp({mantissa: priceCollateralMantissa}), Exp({mantissa: exchangeRateMantissa})); Exp memory ratio = div_(numerator, denominator); uint256 seizeTokens = mul_ScalarTruncate(ratio, actualRepayAmount); return (uint256(Error.NO_ERROR), seizeTokens); } /*** Admin Functions ***/ /** * @notice Sets a new price oracle for the comptroller * @dev Admin function to set a new price oracle * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setPriceOracle(PriceOracle newOracle) public returns (uint256) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PRICE_ORACLE_OWNER_CHECK); } // Track the old oracle for the comptroller PriceOracle oldOracle = oracle; // Set comptroller's oracle to newOracle oracle = newOracle; // Emit NewPriceOracle(oldOracle, newOracle) emit NewPriceOracle(oldOracle, newOracle); return uint256(Error.NO_ERROR); } /** * @notice Sets the closeFactor used when liquidating borrows * @dev Admin function to set closeFactor * @param newCloseFactorMantissa New close factor, scaled by 1e18 * @return uint 0=success, otherwise a failure. (See ErrorReporter for details) */ function _setCloseFactor(uint256 newCloseFactorMantissa) external returns (uint256) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_CLOSE_FACTOR_OWNER_CHECK); } uint256 oldCloseFactorMantissa = closeFactorMantissa; closeFactorMantissa = newCloseFactorMantissa; emit NewCloseFactor(oldCloseFactorMantissa, closeFactorMantissa); return uint256(Error.NO_ERROR); } /** * @notice Sets the collateralFactor for a market * @dev Admin function to set per-market collateralFactor * @param cToken The market to set the factor on * @param newCollateralFactorMantissa The new collateral factor, scaled by 1e18 * @return uint 0=success, otherwise a failure. (See ErrorReporter for details) */ function _setCollateralFactor(CToken cToken, uint256 newCollateralFactorMantissa) external returns (uint256) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_COLLATERAL_FACTOR_OWNER_CHECK); } // Verify market is listed Market storage market = markets[address(cToken)]; if (!market.isListed) { return fail(Error.MARKET_NOT_LISTED, FailureInfo.SET_COLLATERAL_FACTOR_NO_EXISTS); } Exp memory newCollateralFactorExp = Exp({mantissa: newCollateralFactorMantissa}); // Check collateral factor <= 0.9 Exp memory highLimit = Exp({mantissa: collateralFactorMaxMantissa}); if (lessThanExp(highLimit, newCollateralFactorExp)) { return fail(Error.INVALID_COLLATERAL_FACTOR, FailureInfo.SET_COLLATERAL_FACTOR_VALIDATION); } // If collateral factor != 0, fail if price == 0 if (newCollateralFactorMantissa != 0 && oracle.getUnderlyingPrice(cToken) == 0) { return fail(Error.PRICE_ERROR, FailureInfo.SET_COLLATERAL_FACTOR_WITHOUT_PRICE); } // Set market's collateral factor to new collateral factor, remember old value uint256 oldCollateralFactorMantissa = market.collateralFactorMantissa; market.collateralFactorMantissa = newCollateralFactorMantissa; // Emit event with asset, old collateral factor, and new collateral factor emit NewCollateralFactor(cToken, oldCollateralFactorMantissa, newCollateralFactorMantissa); return uint256(Error.NO_ERROR); } /** * @notice Sets liquidationIncentive * @dev Admin function to set liquidationIncentive * @param newLiquidationIncentiveMantissa New liquidationIncentive scaled by 1e18 * @return uint 0=success, otherwise a failure. (See ErrorReporter for details) */ function _setLiquidationIncentive(uint256 newLiquidationIncentiveMantissa) external returns (uint256) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_LIQUIDATION_INCENTIVE_OWNER_CHECK); } // Save current value for use in log uint256 oldLiquidationIncentiveMantissa = liquidationIncentiveMantissa; // Set liquidation incentive to new incentive liquidationIncentiveMantissa = newLiquidationIncentiveMantissa; // Emit event with old incentive, new incentive emit NewLiquidationIncentive(oldLiquidationIncentiveMantissa, newLiquidationIncentiveMantissa); return uint256(Error.NO_ERROR); } /** * @notice Add the market to the markets mapping and set it as listed * @dev Admin function to set isListed and add support for the market * @param cToken The address of the market (token) to list * @param version The version of the market (token) * @return uint 0=success, otherwise a failure. (See enum Error for details) */ function _supportMarket(CToken cToken, Version version) external returns (uint256) { require(msg.sender == admin, "only admin may support market"); require(!isMarketListed(address(cToken)), "market already listed"); cToken.isCToken(); // Sanity check to make sure its really a CToken markets[address(cToken)] = Market({ isListed: true, isComped: true, collateralFactorMantissa: 0, version: version }); _addMarketInternal(address(cToken)); emit MarketListed(cToken); return uint256(Error.NO_ERROR); } /** * @notice Remove the market from the markets mapping * @param cToken The address of the market (token) to delist */ function _delistMarket(CToken cToken) external { require(msg.sender == admin, "only admin may delist market"); require(isMarketListed(address(cToken)), "market not listed"); require(cToken.totalSupply() == 0, "market not empty"); cToken.isCToken(); // Sanity check to make sure its really a CToken delete markets[address(cToken)]; for (uint256 i = 0; i < allMarkets.length; i++) { if (allMarkets[i] == cToken) { allMarkets[i] = allMarkets[allMarkets.length - 1]; delete allMarkets[allMarkets.length - 1]; allMarkets.length--; break; } } emit MarketDelisted(cToken); } function _addMarketInternal(address cToken) internal { for (uint256 i = 0; i < allMarkets.length; i++) { require(allMarkets[i] != CToken(cToken), "market already added"); } allMarkets.push(CToken(cToken)); } /** * @notice Admin function to change the Supply Cap Guardian * @param newSupplyCapGuardian The address of the new Supply Cap Guardian */ function _setSupplyCapGuardian(address newSupplyCapGuardian) external { require(msg.sender == admin, "only admin can set supply cap guardian"); // Save current value for inclusion in log address oldSupplyCapGuardian = supplyCapGuardian; // Store supplyCapGuardian with value newSupplyCapGuardian supplyCapGuardian = newSupplyCapGuardian; // Emit NewSupplyCapGuardian(OldSupplyCapGuardian, NewSupplyCapGuardian) emit NewSupplyCapGuardian(oldSupplyCapGuardian, newSupplyCapGuardian); } /** * @notice Set the given supply caps for the given cToken markets. Supplying that brings total supplys to or above supply cap will revert. * @dev Admin or supplyCapGuardian function to set the supply caps. A supply cap of 0 corresponds to unlimited supplying. If the total borrows * already exceeded the cap, it will prevent anyone to borrow. * @param cTokens The addresses of the markets (tokens) to change the supply caps for * @param newSupplyCaps The new supply cap values in underlying to be set. A value of 0 corresponds to unlimited supplying. */ function _setMarketSupplyCaps(CToken[] calldata cTokens, uint256[] calldata newSupplyCaps) external { require( msg.sender == admin || msg.sender == supplyCapGuardian, "only admin or supply cap guardian can set supply caps" ); uint256 numMarkets = cTokens.length; uint256 numSupplyCaps = newSupplyCaps.length; require(numMarkets != 0 && numMarkets == numSupplyCaps, "invalid input"); for (uint256 i = 0; i < numMarkets; i++) { supplyCaps[address(cTokens[i])] = newSupplyCaps[i]; emit NewSupplyCap(cTokens[i], newSupplyCaps[i]); } } /** * @notice Set the given borrow caps for the given cToken markets. Borrowing that brings total borrows to or above borrow cap will revert. * @dev Admin or borrowCapGuardian function to set the borrow caps. A borrow cap of 0 corresponds to unlimited borrowing. If the total supplies * already exceeded the cap, it will prevent anyone to mint. * @param cTokens The addresses of the markets (tokens) to change the borrow caps for * @param newBorrowCaps The new borrow cap values in underlying to be set. A value of 0 corresponds to unlimited borrowing. */ function _setMarketBorrowCaps(CToken[] calldata cTokens, uint256[] calldata newBorrowCaps) external { require( msg.sender == admin || msg.sender == borrowCapGuardian, "only admin or borrow cap guardian can set borrow caps" ); uint256 numMarkets = cTokens.length; uint256 numBorrowCaps = newBorrowCaps.length; require(numMarkets != 0 && numMarkets == numBorrowCaps, "invalid input"); for (uint256 i = 0; i < numMarkets; i++) { borrowCaps[address(cTokens[i])] = newBorrowCaps[i]; emit NewBorrowCap(cTokens[i], newBorrowCaps[i]); } } /** * @notice Admin function to change the Borrow Cap Guardian * @param newBorrowCapGuardian The address of the new Borrow Cap Guardian */ function _setBorrowCapGuardian(address newBorrowCapGuardian) external { require(msg.sender == admin, "only admin can set borrow cap guardian"); // Save current value for inclusion in log address oldBorrowCapGuardian = borrowCapGuardian; // Store borrowCapGuardian with value newBorrowCapGuardian borrowCapGuardian = newBorrowCapGuardian; // Emit NewBorrowCapGuardian(OldBorrowCapGuardian, NewBorrowCapGuardian) emit NewBorrowCapGuardian(oldBorrowCapGuardian, newBorrowCapGuardian); } /** * @notice Admin function to change the Pause Guardian * @param newPauseGuardian The address of the new Pause Guardian * @return uint 0=success, otherwise a failure. (See enum Error for details) */ function _setPauseGuardian(address newPauseGuardian) public returns (uint256) { if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PAUSE_GUARDIAN_OWNER_CHECK); } // Save current value for inclusion in log address oldPauseGuardian = pauseGuardian; // Store pauseGuardian with value newPauseGuardian pauseGuardian = newPauseGuardian; // Emit NewPauseGuardian(OldPauseGuardian, NewPauseGuardian) emit NewPauseGuardian(oldPauseGuardian, pauseGuardian); return uint256(Error.NO_ERROR); } /** * @notice Admin function to set the liquidity mining module address * @dev Removing the liquidity mining module address could cause the inconsistency in the LM module. * @param newLiquidityMining The address of the new liquidity mining module */ function _setLiquidityMining(address newLiquidityMining) external { require(msg.sender == admin, "only admin can set liquidity mining module"); require(LiquidityMiningInterface(newLiquidityMining).comptroller() == address(this), "mismatch comptroller"); // Save current value for inclusion in log address oldLiquidityMining = liquidityMining; // Store pauseGuardian with value newLiquidityMining liquidityMining = newLiquidityMining; // Emit NewLiquidityMining(OldLiquidityMining, NewLiquidityMining) emit NewLiquidityMining(oldLiquidityMining, liquidityMining); } function _setMintPaused(CToken cToken, bool state) public returns (bool) { require(isMarketListed(address(cToken)), "cannot pause a market that is not listed"); require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause"); require(msg.sender == admin || state == true, "only admin can unpause"); mintGuardianPaused[address(cToken)] = state; emit ActionPaused(cToken, "Mint", state); return state; } function _setBorrowPaused(CToken cToken, bool state) public returns (bool) { require(isMarketListed(address(cToken)), "cannot pause a market that is not listed"); require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause"); require(msg.sender == admin || state == true, "only admin can unpause"); borrowGuardianPaused[address(cToken)] = state; emit ActionPaused(cToken, "Borrow", state); return state; } function _setFlashloanPaused(CToken cToken, bool state) public returns (bool) { require(isMarketListed(address(cToken)), "cannot pause a market that is not listed"); require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause"); require(msg.sender == admin || state == true, "only admin can unpause"); flashloanGuardianPaused[address(cToken)] = state; emit ActionPaused(cToken, "Flashloan", state); return state; } function _setTransferPaused(bool state) public returns (bool) { require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause"); require(msg.sender == admin || state == true, "only admin can unpause"); transferGuardianPaused = state; emit ActionPaused("Transfer", state); return state; } function _setSeizePaused(bool state) public returns (bool) { require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause"); require(msg.sender == admin || state == true, "only admin can unpause"); seizeGuardianPaused = state; emit ActionPaused("Seize", state); return state; } function _become(Unitroller unitroller) public { require(msg.sender == unitroller.admin(), "only unitroller admin can change brains"); require(unitroller._acceptImplementation() == 0, "change not authorized"); } /*** Comp Distribution ***/ /** * @notice Calculate COMP accrued by a supplier and possibly transfer it to them * @param cToken The market in which the supplier is interacting * @param supplier The address of the supplier to distribute COMP to */ function distributeSupplierComp(address cToken, address supplier) internal { // We won't relaunch LM program on comptroller again. Do nothing if the user's supplierIndex is 0. if (compSupplierIndex[cToken][supplier] == 0) { return; } CompMarketState storage supplyState = compSupplyState[cToken]; Double memory supplyIndex = Double({mantissa: supplyState.index}); Double memory supplierIndex = Double({mantissa: compSupplierIndex[cToken][supplier]}); compSupplierIndex[cToken][supplier] = supplyIndex.mantissa; if (supplierIndex.mantissa == 0 && supplyIndex.mantissa > 0) { supplierIndex.mantissa = compInitialIndex; } Double memory deltaIndex = sub_(supplyIndex, supplierIndex); uint256 supplierTokens = CToken(cToken).balanceOf(supplier); uint256 supplierDelta = mul_(supplierTokens, deltaIndex); uint256 supplierAccrued = add_(compAccrued[supplier], supplierDelta); compAccrued[supplier] = transferComp(supplier, supplierAccrued); emit DistributedSupplierComp(CToken(cToken), supplier, supplierDelta, supplyIndex.mantissa); } /** * @notice Calculate COMP accrued by a borrower and possibly transfer it to them * @dev Borrowers will not begin to accrue until after the first interaction with the protocol. * @param cToken The market in which the borrower is interacting * @param borrower The address of the borrower to distribute COMP to */ function distributeBorrowerComp( address cToken, address borrower, Exp memory marketBorrowIndex ) internal { // We won't relaunch LM program on comptroller again. Do nothing if the user's borrowerIndex is 0. if (compBorrowerIndex[cToken][borrower] == 0) { return; } CompMarketState storage borrowState = compBorrowState[cToken]; Double memory borrowIndex = Double({mantissa: borrowState.index}); Double memory borrowerIndex = Double({mantissa: compBorrowerIndex[cToken][borrower]}); compBorrowerIndex[cToken][borrower] = borrowIndex.mantissa; if (borrowerIndex.mantissa > 0) { Double memory deltaIndex = sub_(borrowIndex, borrowerIndex); uint256 borrowerAmount = div_(CToken(cToken).borrowBalanceStored(borrower), marketBorrowIndex); uint256 borrowerDelta = mul_(borrowerAmount, deltaIndex); uint256 borrowerAccrued = add_(compAccrued[borrower], borrowerDelta); compAccrued[borrower] = transferComp(borrower, borrowerAccrued); emit DistributedBorrowerComp(CToken(cToken), borrower, borrowerDelta, borrowIndex.mantissa); } } /** * @notice Transfer COMP to the user, if they are above the threshold * @dev Note: If there is not enough COMP, we do not perform the transfer all. * @param user The address of the user to transfer COMP to * @param userAccrued The amount of COMP to (possibly) transfer * @return The amount of COMP which was NOT transferred to the user */ function transferComp(address user, uint256 userAccrued) internal returns (uint256) { if (userAccrued > 0) { Comp comp = Comp(getCompAddress()); uint256 compRemaining = comp.balanceOf(address(this)); if (userAccrued <= compRemaining) { comp.transfer(user, userAccrued); return 0; } } return userAccrued; } /** * @notice Claim all the comp accrued by holder in all markets * @param holder The address to claim COMP for */ function claimComp(address holder) public { address[] memory holders = new address[](1); holders[0] = holder; return claimComp(holders, allMarkets, true, true); } /** * @notice Claim all comp accrued by the holders * @param holders The addresses to claim COMP for * @param cTokens The list of markets to claim COMP in * @param borrowers Whether or not to claim COMP earned by borrowing * @param suppliers Whether or not to claim COMP earned by supplying */ function claimComp( address[] memory holders, CToken[] memory cTokens, bool borrowers, bool suppliers ) public { for (uint256 i = 0; i < cTokens.length; i++) { CToken cToken = cTokens[i]; require(isMarketListed(address(cToken)), "market must be listed"); if (borrowers == true) { Exp memory borrowIndex = Exp({mantissa: cToken.borrowIndex()}); for (uint256 j = 0; j < holders.length; j++) { distributeBorrowerComp(address(cToken), holders[j], borrowIndex); } } if (suppliers == true) { for (uint256 j = 0; j < holders.length; j++) { distributeSupplierComp(address(cToken), holders[j]); } } } } /** * @notice Return all of the markets * @dev The automatic getter may be used to access an individual market. * @return The list of market addresses */ function getAllMarkets() public view returns (CToken[] memory) { return allMarkets; } function getBlockNumber() public view returns (uint256) { return block.number; } /** * @notice Return the address of the COMP token * @return The address of COMP */ function getCompAddress() public view returns (address) { return 0x2ba592F78dB6436527729929AAf6c908497cB200; } } pragma solidity ^0.5.16; import "./CToken.sol"; import "./ComptrollerStorage.sol"; contract ComptrollerInterface { /// @notice Indicator that this is a Comptroller contract (for inspection) bool public constant isComptroller = true; /*** Assets You Are In ***/ function enterMarkets(address[] calldata cTokens) external returns (uint256[] memory); function exitMarket(address cToken) external returns (uint256); /*** Policy Hooks ***/ function mintAllowed( address cToken, address minter, uint256 mintAmount ) external returns (uint256); function mintVerify( address cToken, address minter, uint256 mintAmount, uint256 mintTokens ) external; function redeemAllowed( address cToken, address redeemer, uint256 redeemTokens ) external returns (uint256); function redeemVerify( address cToken, address redeemer, uint256 redeemAmount, uint256 redeemTokens ) external; function borrowAllowed( address cToken, address borrower, uint256 borrowAmount ) external returns (uint256); function borrowVerify( address cToken, address borrower, uint256 borrowAmount ) external; function repayBorrowAllowed( address cToken, address payer, address borrower, uint256 repayAmount ) external returns (uint256); function repayBorrowVerify( address cToken, address payer, address borrower, uint256 repayAmount, uint256 borrowerIndex ) external; function liquidateBorrowAllowed( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint256 repayAmount ) external returns (uint256); function liquidateBorrowVerify( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint256 repayAmount, uint256 seizeTokens ) external; function seizeAllowed( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint256 seizeTokens ) external returns (uint256); function seizeVerify( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint256 seizeTokens ) external; function transferAllowed( address cToken, address src, address dst, uint256 transferTokens ) external returns (uint256); function transferVerify( address cToken, address src, address dst, uint256 transferTokens ) external; /*** Liquidity/Liquidation Calculations ***/ function liquidateCalculateSeizeTokens( address cTokenBorrowed, address cTokenCollateral, uint256 repayAmount ) external view returns (uint256, uint256); } interface ComptrollerInterfaceExtension { function checkMembership(address account, CToken cToken) external view returns (bool); function updateCTokenVersion(address cToken, ComptrollerV2Storage.Version version) external; function flashloanAllowed( address cToken, address receiver, uint256 amount, bytes calldata params ) external view returns (bool); function getAccountLiquidity(address account) external view returns ( uint256, uint256, uint256 ); } pragma solidity ^0.5.16; import "./CToken.sol"; import "./PriceOracle/PriceOracle.sol"; contract UnitrollerAdminStorage { /** * @notice Administrator for this contract */ address public admin; /** * @notice Pending administrator for this contract */ address public pendingAdmin; /** * @notice Active brains of Unitroller */ address public comptrollerImplementation; /** * @notice Pending brains of Unitroller */ address public pendingComptrollerImplementation; } contract ComptrollerV1Storage is UnitrollerAdminStorage { /** * @notice Oracle which gives the price of any given asset */ PriceOracle public oracle; /** * @notice Multiplier used to calculate the maximum repayAmount when liquidating a borrow */ uint256 public closeFactorMantissa; /** * @notice Multiplier representing the discount on collateral that a liquidator receives */ uint256 public liquidationIncentiveMantissa; /** * @notice Max number of assets a single account can participate in (borrow or use as collateral) */ uint256 public maxAssets; /** * @notice Per-account mapping of "assets you are in", capped by maxAssets */ mapping(address => CToken[]) public accountAssets; } contract ComptrollerV2Storage is ComptrollerV1Storage { enum Version { VANILLA, COLLATERALCAP, WRAPPEDNATIVE } struct Market { /// @notice Whether or not this market is listed bool isListed; /** * @notice Multiplier representing the most one can borrow against their collateral in this market. * For instance, 0.9 to allow borrowing 90% of collateral value. * Must be between 0 and 1, and stored as a mantissa. */ uint256 collateralFactorMantissa; /// @notice Per-market mapping of "accounts in this asset" mapping(address => bool) accountMembership; /// @notice Whether or not this market receives COMP bool isComped; /// @notice CToken version Version version; } /** * @notice Official mapping of cTokens -> Market metadata * @dev Used e.g. to determine if a market is supported */ mapping(address => Market) public markets; /** * @notice The Pause Guardian can pause certain actions as a safety mechanism. * Actions which allow users to remove their own assets cannot be paused. * Liquidation / seizing / transfer can only be paused globally, not by market. */ address public pauseGuardian; bool public _mintGuardianPaused; bool public _borrowGuardianPaused; bool public transferGuardianPaused; bool public seizeGuardianPaused; mapping(address => bool) public mintGuardianPaused; mapping(address => bool) public borrowGuardianPaused; } contract ComptrollerV3Storage is ComptrollerV2Storage { struct CompMarketState { /// @notice The market's last updated compBorrowIndex or compSupplyIndex uint224 index; /// @notice The block number the index was last updated at uint32 block; } /// @notice A list of all markets CToken[] public allMarkets; /// @notice The rate at which the flywheel distributes COMP, per block uint256 public compRate; /// @notice The portion of compRate that each market currently receives mapping(address => uint256) public compSpeeds; /// @notice The COMP market supply state for each market mapping(address => CompMarketState) public compSupplyState; /// @notice The COMP market borrow state for each market mapping(address => CompMarketState) public compBorrowState; /// @notice The COMP borrow index for each market for each supplier as of the last time they accrued COMP mapping(address => mapping(address => uint256)) public compSupplierIndex; /// @notice The COMP borrow index for each market for each borrower as of the last time they accrued COMP mapping(address => mapping(address => uint256)) public compBorrowerIndex; /// @notice The COMP accrued but not yet transferred to each user mapping(address => uint256) public compAccrued; } contract ComptrollerV4Storage is ComptrollerV3Storage { // @notice The borrowCapGuardian can set borrowCaps to any number for any market. Lowering the borrow cap could disable borrowing on the given market. address public borrowCapGuardian; // @notice Borrow caps enforced by borrowAllowed for each cToken address. Defaults to zero which corresponds to unlimited borrowing. mapping(address => uint256) public borrowCaps; } contract ComptrollerV5Storage is ComptrollerV4Storage { // @notice The supplyCapGuardian can set supplyCaps to any number for any market. Lowering the supply cap could disable supplying to the given market. address public supplyCapGuardian; // @notice Supply caps enforced by mintAllowed for each cToken address. Defaults to zero which corresponds to unlimited supplying. mapping(address => uint256) public supplyCaps; } contract ComptrollerV6Storage is ComptrollerV5Storage { // @notice flashloanGuardianPaused can pause flash loan as a safety mechanism. mapping(address => bool) public flashloanGuardianPaused; } contract ComptrollerV7Storage is ComptrollerV6Storage { /// @notice liquidityMining the liquidity mining module that handles the LM rewards distribution. address public liquidityMining; } pragma solidity ^0.5.16; /** * @title ERC 20 Token Standard Interface * https://eips.ethereum.org/EIPS/eip-20 */ interface EIP20Interface { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); /** * @notice Get the total number of tokens in circulation * @return The supply of tokens */ function totalSupply() external view returns (uint256); /** * @notice Gets the balance of the specified address * @param owner The address from which the balance will be retrieved * @return The balance */ function balanceOf(address owner) external view returns (uint256 balance); /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint256 amount) external returns (bool success); /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom( address src, address dst, uint256 amount ) external returns (bool success); /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved (-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint256 amount) external returns (bool success); /** * @notice Get the current allowance from `owner` for `spender` * @param owner The address of the account which owns the tokens to be spent * @param spender The address of the account which may transfer tokens * @return The number of tokens allowed to be spent (-1 means infinite) */ function allowance(address owner, address spender) external view returns (uint256 remaining); event Transfer(address indexed from, address indexed to, uint256 amount); event Approval(address indexed owner, address indexed spender, uint256 amount); } pragma solidity ^0.5.16; /** * @title EIP20NonStandardInterface * @dev Version of ERC20 with no return values for `transfer` and `transferFrom` * See https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */ interface EIP20NonStandardInterface { /** * @notice Get the total number of tokens in circulation * @return The supply of tokens */ function totalSupply() external view returns (uint256); /** * @notice Gets the balance of the specified address * @param owner The address from which the balance will be retrieved * @return The balance */ function balanceOf(address owner) external view returns (uint256 balance); /// /// !!!!!!!!!!!!!! /// !!! NOTICE !!! `transfer` does not return a value, in violation of the ERC-20 specification /// !!!!!!!!!!!!!! /// /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer */ function transfer(address dst, uint256 amount) external; /// /// !!!!!!!!!!!!!! /// !!! NOTICE !!! `transferFrom` does not return a value, in violation of the ERC-20 specification /// !!!!!!!!!!!!!! /// /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer */ function transferFrom( address src, address dst, uint256 amount ) external; /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved * @return Whether or not the approval succeeded */ function approve(address spender, uint256 amount) external returns (bool success); /** * @notice Get the current allowance from `owner` for `spender` * @param owner The address of the account which owns the tokens to be spent * @param spender The address of the account which may transfer tokens * @return The number of tokens allowed to be spent */ function allowance(address owner, address spender) external view returns (uint256 remaining); event Transfer(address indexed from, address indexed to, uint256 amount); event Approval(address indexed owner, address indexed spender, uint256 amount); } pragma solidity ^0.5.16; interface ERC3156FlashBorrowerInterface { /** * @dev Receive a flash loan. * @param initiator The initiator of the loan. * @param token The loan currency. * @param amount The amount of tokens lent. * @param fee The additional amount of tokens to repay. * @param data Arbitrary data structure, intended to contain user-defined parameters. * @return The keccak256 hash of "ERC3156FlashBorrower.onFlashLoan" */ function onFlashLoan( address initiator, address token, uint256 amount, uint256 fee, bytes calldata data ) external returns (bytes32); } pragma solidity ^0.5.16; contract ComptrollerErrorReporter { enum Error { NO_ERROR, UNAUTHORIZED, COMPTROLLER_MISMATCH, INSUFFICIENT_SHORTFALL, INSUFFICIENT_LIQUIDITY, INVALID_CLOSE_FACTOR, INVALID_COLLATERAL_FACTOR, INVALID_LIQUIDATION_INCENTIVE, MARKET_NOT_ENTERED, // no longer possible MARKET_NOT_LISTED, MARKET_ALREADY_LISTED, MATH_ERROR, NONZERO_BORROW_BALANCE, PRICE_ERROR, REJECTION, SNAPSHOT_ERROR, TOO_MANY_ASSETS, TOO_MUCH_REPAY } enum FailureInfo { ACCEPT_ADMIN_PENDING_ADMIN_CHECK, ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK, EXIT_MARKET_BALANCE_OWED, EXIT_MARKET_REJECTION, SET_CLOSE_FACTOR_OWNER_CHECK, SET_CLOSE_FACTOR_VALIDATION, SET_COLLATERAL_FACTOR_OWNER_CHECK, SET_COLLATERAL_FACTOR_NO_EXISTS, SET_COLLATERAL_FACTOR_VALIDATION, SET_COLLATERAL_FACTOR_WITHOUT_PRICE, SET_IMPLEMENTATION_OWNER_CHECK, SET_LIQUIDATION_INCENTIVE_OWNER_CHECK, SET_LIQUIDATION_INCENTIVE_VALIDATION, SET_MAX_ASSETS_OWNER_CHECK, SET_PENDING_ADMIN_OWNER_CHECK, SET_PENDING_IMPLEMENTATION_OWNER_CHECK, SET_PRICE_ORACLE_OWNER_CHECK, SUPPORT_MARKET_EXISTS, SUPPORT_MARKET_OWNER_CHECK, SET_PAUSE_GUARDIAN_OWNER_CHECK } /** * @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary * contract-specific code that enables us to report opaque error codes from upgradeable contracts. **/ event Failure(uint256 error, uint256 info, uint256 detail); /** * @dev use this when reporting a known error from the money market or a non-upgradeable collaborator */ function fail(Error err, FailureInfo info) internal returns (uint256) { emit Failure(uint256(err), uint256(info), 0); return uint256(err); } /** * @dev use this when reporting an opaque error from an upgradeable collaborator contract */ function failOpaque( Error err, FailureInfo info, uint256 opaqueError ) internal returns (uint256) { emit Failure(uint256(err), uint256(info), opaqueError); return uint256(err); } } contract TokenErrorReporter { enum Error { NO_ERROR, UNAUTHORIZED, BAD_INPUT, COMPTROLLER_REJECTION, COMPTROLLER_CALCULATION_ERROR, INTEREST_RATE_MODEL_ERROR, INVALID_ACCOUNT_PAIR, INVALID_CLOSE_AMOUNT_REQUESTED, INVALID_COLLATERAL_FACTOR, MATH_ERROR, MARKET_NOT_FRESH, MARKET_NOT_LISTED, TOKEN_INSUFFICIENT_ALLOWANCE, TOKEN_INSUFFICIENT_BALANCE, TOKEN_INSUFFICIENT_CASH, TOKEN_TRANSFER_IN_FAILED, TOKEN_TRANSFER_OUT_FAILED } /* * Note: FailureInfo (but not Error) is kept in alphabetical order * This is because FailureInfo grows significantly faster, and * the order of Error has some meaning, while the order of FailureInfo * is entirely arbitrary. */ enum FailureInfo { ACCEPT_ADMIN_PENDING_ADMIN_CHECK, ACCRUE_INTEREST_BORROW_RATE_CALCULATION_FAILED, BORROW_ACCRUE_INTEREST_FAILED, BORROW_CASH_NOT_AVAILABLE, BORROW_FRESHNESS_CHECK, BORROW_MARKET_NOT_LISTED, BORROW_COMPTROLLER_REJECTION, LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED, LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED, LIQUIDATE_COLLATERAL_FRESHNESS_CHECK, LIQUIDATE_COMPTROLLER_REJECTION, LIQUIDATE_COMPTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED, LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX, LIQUIDATE_CLOSE_AMOUNT_IS_ZERO, LIQUIDATE_FRESHNESS_CHECK, LIQUIDATE_LIQUIDATOR_IS_BORROWER, LIQUIDATE_REPAY_BORROW_FRESH_FAILED, LIQUIDATE_SEIZE_COMPTROLLER_REJECTION, LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER, LIQUIDATE_SEIZE_TOO_MUCH, MINT_ACCRUE_INTEREST_FAILED, MINT_COMPTROLLER_REJECTION, MINT_FRESHNESS_CHECK, MINT_TRANSFER_IN_FAILED, MINT_TRANSFER_IN_NOT_POSSIBLE, REDEEM_ACCRUE_INTEREST_FAILED, REDEEM_COMPTROLLER_REJECTION, REDEEM_FRESHNESS_CHECK, REDEEM_TRANSFER_OUT_NOT_POSSIBLE, REDUCE_RESERVES_ACCRUE_INTEREST_FAILED, REDUCE_RESERVES_ADMIN_CHECK, REDUCE_RESERVES_CASH_NOT_AVAILABLE, REDUCE_RESERVES_FRESH_CHECK, REDUCE_RESERVES_VALIDATION, REPAY_BEHALF_ACCRUE_INTEREST_FAILED, REPAY_BORROW_ACCRUE_INTEREST_FAILED, REPAY_BORROW_COMPTROLLER_REJECTION, REPAY_BORROW_FRESHNESS_CHECK, REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE, SET_COLLATERAL_FACTOR_OWNER_CHECK, SET_COLLATERAL_FACTOR_VALIDATION, SET_COMPTROLLER_OWNER_CHECK, SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED, SET_INTEREST_RATE_MODEL_FRESH_CHECK, SET_INTEREST_RATE_MODEL_OWNER_CHECK, SET_MAX_ASSETS_OWNER_CHECK, SET_ORACLE_MARKET_NOT_LISTED, SET_PENDING_ADMIN_OWNER_CHECK, SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED, SET_RESERVE_FACTOR_ADMIN_CHECK, SET_RESERVE_FACTOR_FRESH_CHECK, SET_RESERVE_FACTOR_BOUNDS_CHECK, TRANSFER_COMPTROLLER_REJECTION, TRANSFER_NOT_ALLOWED, ADD_RESERVES_ACCRUE_INTEREST_FAILED, ADD_RESERVES_FRESH_CHECK, ADD_RESERVES_TRANSFER_IN_NOT_POSSIBLE } /** * @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary * contract-specific code that enables us to report opaque error codes from upgradeable contracts. **/ event Failure(uint256 error, uint256 info, uint256 detail); /** * @dev use this when reporting a known error from the money market or a non-upgradeable collaborator */ function fail(Error err, FailureInfo info) internal returns (uint256) { emit Failure(uint256(err), uint256(info), 0); return uint256(err); } /** * @dev use this when reporting an opaque error from an upgradeable collaborator contract */ function failOpaque( Error err, FailureInfo info, uint256 opaqueError ) internal returns (uint256) { emit Failure(uint256(err), uint256(info), opaqueError); return uint256(err); } } pragma solidity ^0.5.16; import "./CarefulMath.sol"; /** * @title Exponential module for storing fixed-precision decimals * @author Compound * @notice Exp is a struct which stores decimals with a fixed precision of 18 decimal places. * Thus, if we wanted to store the 5.1, mantissa would store 5.1e18. That is: * `Exp({mantissa: 5100000000000000000})`. */ contract Exponential is CarefulMath { uint256 constant expScale = 1e18; uint256 constant doubleScale = 1e36; uint256 constant halfExpScale = expScale / 2; uint256 constant mantissaOne = expScale; struct Exp { uint256 mantissa; } struct Double { uint256 mantissa; } /** * @dev Creates an exponential from numerator and denominator values. * Note: Returns an error if (`num` * 10e18) > MAX_INT, * or if `denom` is zero. */ function getExp(uint256 num, uint256 denom) internal pure returns (MathError, Exp memory) { (MathError err0, uint256 scaledNumerator) = mulUInt(num, expScale); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } (MathError err1, uint256 rational) = divUInt(scaledNumerator, denom); if (err1 != MathError.NO_ERROR) { return (err1, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: rational})); } /** * @dev Adds two exponentials, returning a new exponential. */ function addExp(Exp memory a, Exp memory b) internal pure returns (MathError, Exp memory) { (MathError error, uint256 result) = addUInt(a.mantissa, b.mantissa); return (error, Exp({mantissa: result})); } /** * @dev Subtracts two exponentials, returning a new exponential. */ function subExp(Exp memory a, Exp memory b) internal pure returns (MathError, Exp memory) { (MathError error, uint256 result) = subUInt(a.mantissa, b.mantissa); return (error, Exp({mantissa: result})); } /** * @dev Multiply an Exp by a scalar, returning a new Exp. */ function mulScalar(Exp memory a, uint256 scalar) internal pure returns (MathError, Exp memory) { (MathError err0, uint256 scaledMantissa) = mulUInt(a.mantissa, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: scaledMantissa})); } /** * @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer. */ function mulScalarTruncate(Exp memory a, uint256 scalar) internal pure returns (MathError, uint256) { (MathError err, Exp memory product) = mulScalar(a, scalar); if (err != MathError.NO_ERROR) { return (err, 0); } return (MathError.NO_ERROR, truncate(product)); } /** * @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer. */ function mulScalarTruncateAddUInt( Exp memory a, uint256 scalar, uint256 addend ) internal pure returns (MathError, uint256) { (MathError err, Exp memory product) = mulScalar(a, scalar); if (err != MathError.NO_ERROR) { return (err, 0); } return addUInt(truncate(product), addend); } /** * @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer. */ function mul_ScalarTruncate(Exp memory a, uint256 scalar) internal pure returns (uint256) { Exp memory product = mul_(a, scalar); return truncate(product); } /** * @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer. */ function mul_ScalarTruncateAddUInt( Exp memory a, uint256 scalar, uint256 addend ) internal pure returns (uint256) { Exp memory product = mul_(a, scalar); return add_(truncate(product), addend); } /** * @dev Divide an Exp by a scalar, returning a new Exp. */ function divScalar(Exp memory a, uint256 scalar) internal pure returns (MathError, Exp memory) { (MathError err0, uint256 descaledMantissa) = divUInt(a.mantissa, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: descaledMantissa})); } /** * @dev Divide a scalar by an Exp, returning a new Exp. */ function divScalarByExp(uint256 scalar, Exp memory divisor) internal pure returns (MathError, Exp memory) { /* We are doing this as: getExp(mulUInt(expScale, scalar), divisor.mantissa) How it works: Exp = a / b; Scalar = s; `s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale` */ (MathError err0, uint256 numerator) = mulUInt(expScale, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return getExp(numerator, divisor.mantissa); } /** * @dev Divide a scalar by an Exp, then truncate to return an unsigned integer. */ function divScalarByExpTruncate(uint256 scalar, Exp memory divisor) internal pure returns (MathError, uint256) { (MathError err, Exp memory fraction) = divScalarByExp(scalar, divisor); if (err != MathError.NO_ERROR) { return (err, 0); } return (MathError.NO_ERROR, truncate(fraction)); } /** * @dev Divide a scalar by an Exp, returning a new Exp. */ function div_ScalarByExp(uint256 scalar, Exp memory divisor) internal pure returns (Exp memory) { /* We are doing this as: getExp(mulUInt(expScale, scalar), divisor.mantissa) How it works: Exp = a / b; Scalar = s; `s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale` */ uint256 numerator = mul_(expScale, scalar); return Exp({mantissa: div_(numerator, divisor)}); } /** * @dev Divide a scalar by an Exp, then truncate to return an unsigned integer. */ function div_ScalarByExpTruncate(uint256 scalar, Exp memory divisor) internal pure returns (uint256) { Exp memory fraction = div_ScalarByExp(scalar, divisor); return truncate(fraction); } /** * @dev Multiplies two exponentials, returning a new exponential. */ function mulExp(Exp memory a, Exp memory b) internal pure returns (MathError, Exp memory) { (MathError err0, uint256 doubleScaledProduct) = mulUInt(a.mantissa, b.mantissa); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } // We add half the scale before dividing so that we get rounding instead of truncation. // See "Listing 6" and text above it at https://accu.org/index.php/journals/1717 // Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18. (MathError err1, uint256 doubleScaledProductWithHalfScale) = addUInt(halfExpScale, doubleScaledProduct); if (err1 != MathError.NO_ERROR) { return (err1, Exp({mantissa: 0})); } (MathError err2, uint256 product) = divUInt(doubleScaledProductWithHalfScale, expScale); // The only error `div` can return is MathError.DIVISION_BY_ZERO but we control `expScale` and it is not zero. assert(err2 == MathError.NO_ERROR); return (MathError.NO_ERROR, Exp({mantissa: product})); } /** * @dev Multiplies two exponentials given their mantissas, returning a new exponential. */ function mulExp(uint256 a, uint256 b) internal pure returns (MathError, Exp memory) { return mulExp(Exp({mantissa: a}), Exp({mantissa: b})); } /** * @dev Multiplies three exponentials, returning a new exponential. */ function mulExp3( Exp memory a, Exp memory b, Exp memory c ) internal pure returns (MathError, Exp memory) { (MathError err, Exp memory ab) = mulExp(a, b); if (err != MathError.NO_ERROR) { return (err, ab); } return mulExp(ab, c); } /** * @dev Divides two exponentials, returning a new exponential. * (a/scale) / (b/scale) = (a/scale) * (scale/b) = a/b, * which we can scale as an Exp by calling getExp(a.mantissa, b.mantissa) */ function divExp(Exp memory a, Exp memory b) internal pure returns (MathError, Exp memory) { return getExp(a.mantissa, b.mantissa); } /** * @dev Truncates the given exp to a whole number value. * For example, truncate(Exp{mantissa: 15 * expScale}) = 15 */ function truncate(Exp memory exp) internal pure returns (uint256) { // Note: We are not using careful math here as we're performing a division that cannot fail return exp.mantissa / expScale; } /** * @dev Checks if first Exp is less than second Exp. */ function lessThanExp(Exp memory left, Exp memory right) internal pure returns (bool) { return left.mantissa < right.mantissa; } /** * @dev Checks if left Exp <= right Exp. */ function lessThanOrEqualExp(Exp memory left, Exp memory right) internal pure returns (bool) { return left.mantissa <= right.mantissa; } /** * @dev returns true if Exp is exactly zero */ function isZeroExp(Exp memory value) internal pure returns (bool) { return value.mantissa == 0; } function safe224(uint256 n, string memory errorMessage) internal pure returns (uint224) { require(n < 2**224, errorMessage); return uint224(n); } function safe32(uint256 n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function add_(Exp memory a, Exp memory b) internal pure returns (Exp memory) { return Exp({mantissa: add_(a.mantissa, b.mantissa)}); } function add_(Double memory a, Double memory b) internal pure returns (Double memory) { return Double({mantissa: add_(a.mantissa, b.mantissa)}); } function add_(uint256 a, uint256 b) internal pure returns (uint256) { return add_(a, b, "addition overflow"); } function add_( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, errorMessage); return c; } function sub_(Exp memory a, Exp memory b) internal pure returns (Exp memory) { return Exp({mantissa: sub_(a.mantissa, b.mantissa)}); } function sub_(Double memory a, Double memory b) internal pure returns (Double memory) { return Double({mantissa: sub_(a.mantissa, b.mantissa)}); } function sub_(uint256 a, uint256 b) internal pure returns (uint256) { return sub_(a, b, "subtraction underflow"); } function sub_( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } function mul_(Exp memory a, Exp memory b) internal pure returns (Exp memory) { return Exp({mantissa: mul_(a.mantissa, b.mantissa) / expScale}); } function mul_(Exp memory a, uint256 b) internal pure returns (Exp memory) { return Exp({mantissa: mul_(a.mantissa, b)}); } function mul_(uint256 a, Exp memory b) internal pure returns (uint256) { return mul_(a, b.mantissa) / expScale; } function mul_(Double memory a, Double memory b) internal pure returns (Double memory) { return Double({mantissa: mul_(a.mantissa, b.mantissa) / doubleScale}); } function mul_(Double memory a, uint256 b) internal pure returns (Double memory) { return Double({mantissa: mul_(a.mantissa, b)}); } function mul_(uint256 a, Double memory b) internal pure returns (uint256) { return mul_(a, b.mantissa) / doubleScale; } function mul_(uint256 a, uint256 b) internal pure returns (uint256) { return mul_(a, b, "multiplication overflow"); } function mul_( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { if (a == 0 || b == 0) { return 0; } uint256 c = a * b; require(c / a == b, errorMessage); return c; } function div_(Exp memory a, Exp memory b) internal pure returns (Exp memory) { return Exp({mantissa: div_(mul_(a.mantissa, expScale), b.mantissa)}); } function div_(Exp memory a, uint256 b) internal pure returns (Exp memory) { return Exp({mantissa: div_(a.mantissa, b)}); } function div_(uint256 a, Exp memory b) internal pure returns (uint256) { return div_(mul_(a, expScale), b.mantissa); } function div_(Double memory a, Double memory b) internal pure returns (Double memory) { return Double({mantissa: div_(mul_(a.mantissa, doubleScale), b.mantissa)}); } function div_(Double memory a, uint256 b) internal pure returns (Double memory) { return Double({mantissa: div_(a.mantissa, b)}); } function div_(uint256 a, Double memory b) internal pure returns (uint256) { return div_(mul_(a, doubleScale), b.mantissa); } function div_(uint256 a, uint256 b) internal pure returns (uint256) { return div_(a, b, "divide by zero"); } function div_( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } function fraction(uint256 a, uint256 b) internal pure returns (Double memory) { return Double({mantissa: div_(mul_(a, doubleScale), b)}); } // implementation from https://github.com/Uniswap/uniswap-lib/commit/99f3f28770640ba1bb1ff460ac7c5292fb8291a0 // original implementation: https://github.com/abdk-consulting/abdk-libraries-solidity/blob/master/ABDKMath64x64.sol#L687 function sqrt(uint256 x) internal pure returns (uint256) { if (x == 0) return 0; uint256 xx = x; uint256 r = 1; if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; } if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; } if (xx >= 0x100000000) { xx >>= 32; r <<= 16; } if (xx >= 0x10000) { xx >>= 16; r <<= 8; } if (xx >= 0x100) { xx >>= 8; r <<= 4; } if (xx >= 0x10) { xx >>= 4; r <<= 2; } if (xx >= 0x8) { r <<= 1; } r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; // Seven iterations should be enough uint256 r1 = x / r; return (r < r1 ? r : r1); } } pragma solidity ^0.5.16; contract Comp { /// @notice EIP-20 token name for this token string public constant name = "Cream"; /// @notice EIP-20 token symbol for this token string public constant symbol = "CREAM"; /// @notice EIP-20 token decimals for this token uint8 public constant decimals = 18; /// @notice Total number of tokens in circulation uint256 public constant totalSupply = 9000000e18; // 9 million Comp /// @notice Allowance amounts on behalf of others mapping(address => mapping(address => uint96)) internal allowances; /// @notice Official record of token balances for each account mapping(address => uint96) internal balances; /// @notice A record of each accounts delegate mapping(address => address) public delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint96 votes; } /// @notice A record of votes checkpoints for each account, by index mapping(address => mapping(uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping(address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice A record of states for signing / validating signatures mapping(address => uint256) public nonces; /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint256 previousBalance, uint256 newBalance); /// @notice The standard EIP-20 transfer event event Transfer(address indexed from, address indexed to, uint256 amount); /// @notice The standard EIP-20 approval event event Approval(address indexed owner, address indexed spender, uint256 amount); /** * @notice Construct a new Comp token * @param account The initial account to grant all the tokens */ constructor(address account) public { balances[account] = uint96(totalSupply); emit Transfer(address(0), account, totalSupply); } /** * @notice Get the number of tokens `spender` is approved to spend on behalf of `account` * @param account The address of the account holding the funds * @param spender The address of the account spending the funds * @return The number of tokens approved */ function allowance(address account, address spender) external view returns (uint256) { return allowances[account][spender]; } /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param rawAmount The number of tokens that are approved (2^256-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint256 rawAmount) external returns (bool) { uint96 amount; if (rawAmount == uint256(-1)) { amount = uint96(-1); } else { amount = safe96(rawAmount, "Comp::approve: amount exceeds 96 bits"); } allowances[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } /** * @notice Get the number of tokens held by the `account` * @param account The address of the account to get the balance of * @return The number of tokens held */ function balanceOf(address account) external view returns (uint256) { return balances[account]; } /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param rawAmount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint256 rawAmount) external returns (bool) { uint96 amount = safe96(rawAmount, "Comp::transfer: amount exceeds 96 bits"); _transferTokens(msg.sender, dst, amount); return true; } /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param rawAmount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom( address src, address dst, uint256 rawAmount ) external returns (bool) { address spender = msg.sender; uint96 spenderAllowance = allowances[src][spender]; uint96 amount = safe96(rawAmount, "Comp::approve: amount exceeds 96 bits"); if (spender != src && spenderAllowance != uint96(-1)) { uint96 newAllowance = sub96( spenderAllowance, amount, "Comp::transferFrom: transfer amount exceeds spender allowance" ); allowances[src][spender] = newAllowance; emit Approval(src, spender, newAllowance); } _transferTokens(src, dst, amount); return true; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) public { return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig( address delegatee, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s ) public { bytes32 domainSeparator = keccak256( abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this)) ); bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry)); bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "Comp::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "Comp::delegateBySig: invalid nonce"); require(now <= expiry, "Comp::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint96) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint256 blockNumber) public view returns (uint96) { require(blockNumber < block.number, "Comp::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = delegates[delegator]; uint96 delegatorBalance = balances[delegator]; delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _transferTokens( address src, address dst, uint96 amount ) internal { require(src != address(0), "Comp::_transferTokens: cannot transfer from the zero address"); require(dst != address(0), "Comp::_transferTokens: cannot transfer to the zero address"); balances[src] = sub96(balances[src], amount, "Comp::_transferTokens: transfer amount exceeds balance"); balances[dst] = add96(balances[dst], amount, "Comp::_transferTokens: transfer amount overflows"); emit Transfer(src, dst, amount); _moveDelegates(delegates[src], delegates[dst], amount); } function _moveDelegates( address srcRep, address dstRep, uint96 amount ) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { uint32 srcRepNum = numCheckpoints[srcRep]; uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint96 srcRepNew = sub96(srcRepOld, amount, "Comp::_moveVotes: vote amount underflows"); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { uint32 dstRepNum = numCheckpoints[dstRep]; uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint96 dstRepNew = add96(dstRepOld, amount, "Comp::_moveVotes: vote amount overflows"); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes ) internal { uint32 blockNumber = safe32(block.number, "Comp::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint256 n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function safe96(uint256 n, string memory errorMessage) internal pure returns (uint96) { require(n < 2**96, errorMessage); return uint96(n); } function add96( uint96 a, uint96 b, string memory errorMessage ) internal pure returns (uint96) { uint96 c = a + b; require(c >= a, errorMessage); return c; } function sub96( uint96 a, uint96 b, string memory errorMessage ) internal pure returns (uint96) { require(b <= a, errorMessage); return a - b; } function getChainId() internal pure returns (uint256) { uint256 chainId; assembly { chainId := chainid() } return chainId; } } pragma solidity ^0.5.16; /** * @title Compound's InterestRateModel Interface * @author Compound */ contract InterestRateModel { /// @notice Indicator that this is an InterestRateModel contract (for inspection) bool public constant isInterestRateModel = true; /** * @notice Calculates the current borrow interest rate per block * @param cash The total amount of cash the market has * @param borrows The total amount of borrows the market has outstanding * @param reserves The total amnount of reserves the market has * @return The borrow rate per block (as a percentage, and scaled by 1e18) */ function getBorrowRate( uint256 cash, uint256 borrows, uint256 reserves ) external view returns (uint256); /** * @notice Calculates the current supply interest rate per block * @param cash The total amount of cash the market has * @param borrows The total amount of borrows the market has outstanding * @param reserves The total amnount of reserves the market has * @param reserveFactorMantissa The current reserve factor the market has * @return The supply rate per block (as a percentage, and scaled by 1e18) */ function getSupplyRate( uint256 cash, uint256 borrows, uint256 reserves, uint256 reserveFactorMantissa ) external view returns (uint256); } pragma solidity ^0.5.16; contract LiquidityMiningInterface { function comptroller() external view returns (address); function updateSupplyIndex(address cToken, address[] calldata accounts) external; function updateBorrowIndex(address cToken, address[] calldata accounts) external; } pragma solidity ^0.5.16; import "../CToken.sol"; contract PriceOracle { /// @notice Indicator that this is a PriceOracle contract (for inspection) bool public constant isPriceOracle = true; /** * @notice Get the underlying price of a cToken asset * @param cToken The cToken to get the underlying price of * @return The underlying asset price mantissa (scaled by 1e18). * Zero means the price is unavailable. */ function getUnderlyingPrice(CToken cToken) external view returns (uint256); } pragma solidity ^0.5.16; import "./ErrorReporter.sol"; import "./ComptrollerStorage.sol"; /** * @title ComptrollerCore * @dev Storage for the comptroller is at this address, while execution is delegated to the `comptrollerImplementation`. * CTokens should reference this contract as their comptroller. */ contract Unitroller is UnitrollerAdminStorage, ComptrollerErrorReporter { /** * @notice Emitted when pendingComptrollerImplementation is changed */ event NewPendingImplementation(address oldPendingImplementation, address newPendingImplementation); /** * @notice Emitted when pendingComptrollerImplementation is accepted, which means comptroller implementation is updated */ event NewImplementation(address oldImplementation, address newImplementation); /** * @notice Emitted when pendingAdmin is changed */ event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin); /** * @notice Emitted when pendingAdmin is accepted, which means admin is updated */ event NewAdmin(address oldAdmin, address newAdmin); constructor() public { // Set admin to caller admin = msg.sender; } /*** Admin Functions ***/ function _setPendingImplementation(address newPendingImplementation) public returns (uint256) { if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_IMPLEMENTATION_OWNER_CHECK); } address oldPendingImplementation = pendingComptrollerImplementation; pendingComptrollerImplementation = newPendingImplementation; emit NewPendingImplementation(oldPendingImplementation, pendingComptrollerImplementation); return uint256(Error.NO_ERROR); } /** * @notice Accepts new implementation of comptroller. msg.sender must be pendingImplementation * @dev Admin function for new implementation to accept it's role as implementation * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _acceptImplementation() public returns (uint256) { // Check caller is pendingImplementation and pendingImplementation ≠ address(0) if (msg.sender != pendingComptrollerImplementation || pendingComptrollerImplementation == address(0)) { return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK); } // Save current values for inclusion in log address oldImplementation = comptrollerImplementation; address oldPendingImplementation = pendingComptrollerImplementation; comptrollerImplementation = pendingComptrollerImplementation; pendingComptrollerImplementation = address(0); emit NewImplementation(oldImplementation, comptrollerImplementation); emit NewPendingImplementation(oldPendingImplementation, pendingComptrollerImplementation); return uint256(Error.NO_ERROR); } /** * @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @param newPendingAdmin New pending admin. * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setPendingAdmin(address newPendingAdmin) public returns (uint256) { // Check caller = admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK); } // Save current value, if any, for inclusion in log address oldPendingAdmin = pendingAdmin; // Store pendingAdmin with value newPendingAdmin pendingAdmin = newPendingAdmin; // Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin) emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin); return uint256(Error.NO_ERROR); } /** * @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin * @dev Admin function for pending admin to accept role and update admin * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _acceptAdmin() public returns (uint256) { // Check caller is pendingAdmin and pendingAdmin ≠ address(0) if (msg.sender != pendingAdmin || msg.sender == address(0)) { return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_ADMIN_PENDING_ADMIN_CHECK); } // Save current values for inclusion in log address oldAdmin = admin; address oldPendingAdmin = pendingAdmin; // Store admin with value pendingAdmin admin = pendingAdmin; // Clear the pending value pendingAdmin = address(0); emit NewAdmin(oldAdmin, admin); emit NewPendingAdmin(oldPendingAdmin, pendingAdmin); return uint256(Error.NO_ERROR); } /** * @dev Delegates execution to an implementation contract. * It returns to the external caller whatever the implementation returns * or forwards reverts. */ function() external payable { // delegate all other functions to current implementation (bool success, ) = comptrollerImplementation.delegatecall(msg.data); assembly { let free_mem_ptr := mload(0x40) returndatacopy(free_mem_ptr, 0, returndatasize) switch success case 0 { revert(free_mem_ptr, returndatasize) } default { return(free_mem_ptr, returndatasize) } } } }
* @notice Transfer COMP to the user, if they are above the threshold @dev Note: If there is not enough COMP, we do not perform the transfer all. @param user The address of the user to transfer COMP to @param userAccrued The amount of COMP to (possibly) transfer @return The amount of COMP which was NOT transferred to the user/
function transferComp(address user, uint256 userAccrued) internal returns (uint256) { if (userAccrued > 0) { Comp comp = Comp(getCompAddress()); uint256 compRemaining = comp.balanceOf(address(this)); if (userAccrued <= compRemaining) { comp.transfer(user, userAccrued); return 0; } } return userAccrued; }
6,224,147
[ 1, 5912, 13846, 358, 326, 729, 16, 309, 2898, 854, 5721, 326, 5573, 225, 3609, 30, 971, 1915, 353, 486, 7304, 13846, 16, 732, 741, 486, 3073, 326, 7412, 777, 18, 225, 729, 1021, 1758, 434, 326, 729, 358, 7412, 13846, 358, 225, 729, 8973, 86, 5957, 1021, 3844, 434, 13846, 358, 261, 917, 8781, 13, 7412, 327, 1021, 3844, 434, 13846, 1492, 1703, 4269, 906, 4193, 358, 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, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 7412, 2945, 12, 2867, 729, 16, 2254, 5034, 729, 8973, 86, 5957, 13, 2713, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 309, 261, 1355, 8973, 86, 5957, 405, 374, 13, 288, 203, 5411, 5427, 1161, 273, 5427, 12, 588, 2945, 1887, 10663, 203, 5411, 2254, 5034, 1161, 11429, 273, 1161, 18, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 5411, 309, 261, 1355, 8973, 86, 5957, 1648, 1161, 11429, 13, 288, 203, 7734, 1161, 18, 13866, 12, 1355, 16, 729, 8973, 86, 5957, 1769, 203, 7734, 327, 374, 31, 203, 5411, 289, 203, 3639, 289, 203, 3639, 327, 729, 8973, 86, 5957, 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 ]
pragma solidity ^0.5.0; import "openzeppelin-solidity/contracts/token/ERC20/ERC20.sol"; import "openzeppelin-solidity/contracts/lifecycle/Pausable.sol"; import "openzeppelin-solidity/contracts/utils/Address.sol"; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import "openzeppelin-solidity/contracts/cryptography/ECDSA.sol"; /** @author santteegt * @title SuportEth Subscription contract to a publisher content. * @dev Based on the EIP-1337 spec */ contract PublisherSubscription is Pausable { /// Libraries using Address for address; using SafeMath for uint256; using ECDSA for bytes32; /// Subscriber address address public subscriber; /// Subscription status enum SubscriptionStatus { /// Active Subscription ACTIVE, /// Subscriber does not have enough funds (Unused) INACTIVE, /// Subscriber cancelled the subscription CANCELLED } /// Subscription status SubscriptionStatus public subStatus; /// Next valid timestamp to process subscription /// Similar to a nonce that avoids replay attack /// subscriptionHash => next valid block number in terms of timestamp mapping(bytes32 => uint256) public nextValidTimestamp; /// Subscription settings struct Settings { /// publisher contract address publisher; /// token address to process subscription payments address tokenAddress; /// subscription token amount uint256 tokenAmount; /// subscription period in seconds uint256 subscriptionPeriod; } /// Subscription configuration Settings public settings; /// Event fired when subscription payment has been executed event ExecuteSubscription( address indexed subscriber, //subscriber address indexed publisher, //publisher address tokenAddress, //token address uint256 tokenAmount, //token amount uint256 subscriptionPeriod, //subscription period in seconds between payments uint256 gasPrice //the amount of tokens to pay relayer ); /// Event fired when subscription is cancelled event CancelSubscription( address indexed subscriber, //subscriber address indexed publisher, //publisher address tokenAddress, //token address uint256 tokenAmount, //token amount uint256 subscriptionPeriod //subscription period in seconds between payments ); /// Validate if an address belong to a Contract account modifier isContract(address _addr) { require(_addr.isContract()); _; } /// Validate if contract function caller is the owner modifier onlyOwner() { require(msg.sender == subscriber); _; } /// Validate if publisher is calling a method modifier onlyPublisher() { require(msg.sender == settings.publisher); _; } /// Validate if the subscription is not cancelled modifier subscriptionNotCancelled() { require(subStatus != SubscriptionStatus.CANCELLED, "Subscription is cancelled"); _; } /** * @dev Contract constructor * @param _publisher Publisher Contract * @param _tokenAddress Token address * @param _tokenAmount token amount to pay * @param _subscriptionPeriod subscription period */ constructor( address _publisher, address _tokenAddress, uint256 _tokenAmount, uint256 _subscriptionPeriod ) public isContract(_publisher) isContract(_tokenAddress) { subscriber = msg.sender; settings = Settings( _publisher, _tokenAddress, _tokenAmount, _subscriptionPeriod); } /** @dev Executes subscription payment * @param _subscriber Subscriber address * @param _publisher Publisher address * @param _tokenAddress Token address * @param _tokenAmount Token amount * @param _subscriptionPeriod Subscription period in seconds * @param _signature Proof the subscriber signed the meta trasaction * @return bool true if processed */ function executeSubscription( address _subscriber, address _publisher, address _tokenAddress, uint256 _tokenAmount, uint256 _subscriptionPeriod, bytes memory _signature ) public whenNotPaused subscriptionNotCancelled returns (bool success) { // Validate subscription // pulled this out so I have the hash, should be exact code as "isSubscriptionReady" bytes32 subscriptionHash = getSubscriptionHash( _subscriber, _publisher, _tokenAddress, _tokenAmount, _subscriptionPeriod); address signer = getSubscriptionSigner(subscriptionHash, _signature); require(_subscriber == signer, "Invalid Signature"); require(block.timestamp >= nextValidTimestamp[subscriptionHash], "Subscription is not ready"); // if there are requirements from the deployer, let's make sure // those are met exactly // require(settings.publisher == address(0x0) || settings.publisher == _publisher); // require(settings.tokenAddress == address(0x0) || settings.tokenAddress == _tokenAddress); // require(settings.tokenAmount == 0 || settings.tokenAmount == _tokenAmount); // require(settings.subscriptionPeriod == 0 || settings.subscriptionPeriod == _subscriptionPeriod); // require( requiredGasPrice == 0 || gasPrice == requiredGasPrice ); //increment the timestamp by the period so it wont be valid until then nextValidTimestamp[subscriptionHash] = block.timestamp.add(settings.subscriptionPeriod); // now, let make the transfer from the subscriber to the publisher uint256 startingBalance = ERC20(_tokenAddress).balanceOf(_publisher); require(ERC20(_tokenAddress).transferFrom(_subscriber, _publisher, _tokenAmount), "Transfer Failed"); require((startingBalance + _tokenAmount) == ERC20(_tokenAddress).balanceOf(_publisher), "Fatal error during Token Transfer"); uint256 gasPrice = 0; //TODO: include incentives to Relayers based on Oracle and ETH current prize emit ExecuteSubscription( _subscriber, _publisher, _tokenAddress, _tokenAmount, _subscriptionPeriod, gasPrice ); // it is possible for the subscription execution to be run by a third party // incentivized in the terms of the subscription with a gasPrice of the tokens // - pay that out now... if (gasPrice > 0) { //the relayer is incentivized by a little of the same token from // the subscriber ... as far as the subscriber knows, they are // just sending X tokens to the publisher, but the publisher can // choose to send Y of those X to a relayer to run their transactions // the publisher will receive X - Y tokens // this must all be setup in the constructor // if not, the subscriber chooses all the params including what goes // to the publisher and what goes to the relayer require(ERC20(_tokenAddress).transferFrom(_subscriber, msg.sender, gasPrice), "Failed to pay incentive gas token to the relayer"); } return true; } /** @dev Check if a subscription is signed correctly and ready for next execution * @param _subscriber Subscriber address * @param _publisher Publisher address * @param _tokenAddress Token address * @param _tokenAmount Token amount * @param _subscriptionPeriod Subscription period in seconds * @param _signature Proof the subscriber signed the meta trasaction * @return bool true if subscription is ready for payment processing */ function isSubscriptionReady( address _subscriber, address _publisher, address _tokenAddress, uint256 _tokenAmount, uint256 _subscriptionPeriod, bytes memory _signature) public view returns (bool) { bytes32 subscriptionHash = getSubscriptionHash( _subscriber, _publisher, _tokenAddress, _tokenAmount, _subscriptionPeriod); address signer = getSubscriptionSigner(subscriptionHash, _signature); uint256 allowance = ERC20(_tokenAddress).allowance(_subscriber, address(this)); uint256 balance = ERC20(_tokenAddress).balanceOf(_subscriber); return ( signer == _subscriber && _subscriber != _publisher && block.timestamp >= nextValidTimestamp[subscriptionHash] && allowance >= _tokenAmount && balance >= _tokenAmount ); } /** @dev Explicitly cancel the subscription * @notice Subscriber can cancel a subscription any time by not having funds * @param _subscriber Subscriber address * @param _publisher Publisher address * @param _tokenAddress Token address * @param _tokenAmount Token amount * @param _subscriptionPeriod Subscription period in seconds * @param _signature Proof the subscriber signed the meta trasaction * @return success true if processed */ function cancelSubscription( address _subscriber, address _publisher, address _tokenAddress, uint256 _tokenAmount, uint256 _subscriptionPeriod, bytes memory _signature) public onlyOwner subscriptionNotCancelled returns (bool success) { bytes32 subscriptionHash = getSubscriptionHash( _subscriber, _publisher, _tokenAddress, _tokenAmount, _subscriptionPeriod); address signer = getSubscriptionSigner(subscriptionHash, _signature); require(signer == _subscriber, "Invalid Signature"); /// Perform an Integer underflow /// that date will never be reached during human existence nextValidTimestamp[subscriptionHash] = uint256(-1); /// To allow easy queries for subscription status subStatus = SubscriptionStatus.CANCELLED; emit CancelSubscription( _subscriber, _publisher, _tokenAddress, _tokenAmount, _subscriptionPeriod); return true; } /** @dev Generates a hash following the EIP-191 and EIP-1077 standards * @param _subscriber Subscriber address * @param _publisher Publisher address * @param _tokenAddress Token address * @param _tokenAmount Token amount * @param _subscriptionPeriod Subscription period in seconds * @return bytes32 hash from subscription data */ function getSubscriptionHash( address _subscriber, address _publisher, address _tokenAddress, uint256 _tokenAmount, uint256 _subscriptionPeriod ) public view returns (bytes32) { return keccak256( abi.encodePacked( byte(0x19), byte(0), address(this), _subscriber, _publisher, _tokenAddress, _tokenAmount, _subscriptionPeriod)); } /** @dev Executes the ecrecover to get the signer from hash and signature * @param _subscriptionHash Hash of subscription * @param _signature Proof the subscriber signed the meta trasaction * @return address signer address */ function getSubscriptionSigner(bytes32 _subscriptionHash, bytes memory _signature) public pure returns (address) { return _subscriptionHash.toEthSignedMessageHash().recover(_signature); } /** * @dev Low lever version of getSubscriptionSigner method * @notice This function is only intended to show some knowledge on LLL code * @param _subscriptionHash Hash of subscription * @param _signature Proof the subscriber signed the meta trasaction * @return address signer address */ function _getSigner(bytes32 _subscriptionHash, bytes memory _signature) public pure returns (address) { bytes32 r; bytes32 s; uint8 v; if (_signature.length != 65) { return address(0x0); } assembly { r := mload(add(_signature, 32)) s := mload(add(_signature, 64)) v := byte(0, mload(add(_signature, 96))) } if (v < 27) { v += 27; } if (v != 27 && v != 28) { return address(0x0); } else { return ecrecover( keccak256( abi.encodePacked("\x19Ethereum Signed Message:\n32", _subscriptionHash) ), v, r, s); } } /** * @dev Used by external smart contracts to verify on-chain that a * particular subscription is "paid" and "active" * @param _subscriptionHash subscription hash * @param _subscriptionPeriod subscription period in seconds * @return bool true if subscription is active */ function isSubscriptionActive(bytes32 _subscriptionHash, uint256 _subscriptionPeriod) view external returns (bool) { return (block.timestamp <= nextValidTimestamp[_subscriptionHash].add(_subscriptionPeriod) ); } /// @dev Get subscription settings /// @return (address, address, uint256, uint256) Subscription settings function getSettings() external view onlyOwner returns (address, address, uint256, uint256) { return (settings.publisher, settings.tokenAddress, settings.tokenAmount, settings.subscriptionPeriod); } // function getSubscriptionAmount() public view onlyPublisher() returns (uint256) { /// @dev Get subscription amount /// @return uint256 subscription amount function getSubscriptionAmount() public view returns (uint256) { return settings.tokenAmount; } /// @dev This contract does not receive Ether // function() external payable { // revert(); // } }
Libraries Subscriber address Subscription status
enum SubscriptionStatus { ACTIVE, INACTIVE, CANCELLED
15,872,952
[ 1, 31909, 21339, 1758, 12132, 1267, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2792, 12132, 1482, 288, 203, 3639, 21135, 16, 203, 3639, 2120, 13301, 16, 203, 3639, 29641, 6687, 203, 203, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT LICENSE pragma solidity ^0.8.11; import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/security/Pausable.sol"; import "@openzeppelin/contracts/utils/math/Math.sol"; import "./LEGENDZ.sol"; import "./NullHeroes.sol"; import "./HeroStakes.sol"; contract Lands is HeroStakes { constructor(address _legendz, address _nullHeroes) HeroStakes(_legendz, _nullHeroes, 10) { minDaysToClaim = 10 days; } function _resolveReward(uint256 _tokenId) internal override returns (uint256) { return _calculateBaseReward(stakes[_tokenId].lastClaim, _getDailyReward(_tokenId)); } function estimateReward(uint256 _tokenId) public view override returns (uint256) { return _calculateBaseReward(stakes[_tokenId].lastClaim, _getDailyReward(_tokenId)); } function estimateDailyReward() public pure override returns (uint256) { // estimated daily rate on an average of 22 attribute points return 110; } function estimateDailyReward(uint256 _tokenId) public view override returns (uint256) { return _getDailyReward(_tokenId); } /** * calculates the daily reward of a hero * @param _tokenId the tokenId of the hero * return the daily reward of the corresponding hero */ function _getDailyReward(uint256 _tokenId) internal view virtual returns (uint256) { NullHeroes.Hero memory hero = nullHeroes.getHero(_tokenId); return 5 * (hero.force + hero.intelligence + hero.agility); } } // contracts/NullHeroes.sol // SPDX-License-Identifier: MIT pragma solidity ^0.8.11; /** * __ __ __ __ __ __ * /\ "-.\ \ /\ \/\ \ /\ \ /\ \ * \ \ \-. \ \ \ \_\ \ \ \ \____ \ \ \____ * \ \_\\"\_\ \ \_____\ \ \_____\ \ \_____\ * www.\/_/ \/_/ \/_____/ \/_____/ \/_____/ * __ __ ______ ______ ______ ______ ______ * /\ \_\ \ /\ ___\ /\ == \ /\ __ \ /\ ___\ /\ ___\ * \ \ __ \ \ \ __\ \ \ __< \ \ \/\ \ \ \ __\ \ \___ \ * \ \_\ \_\ \ \_____\ \ \_\ \_\ \ \_____\ \ \_____\ \/\_____\ * \/_/\/_/ \/_____/ \/_/ /_/ \/_____/ \/_____/ \/_____/.io * * * Somewhere in the metaverse the null heroes compete to farm the * $LEGENDZ token, an epic ERC20 token that only the bravest will be able * to claim. * * Enroll some heroes and start farming the $LEGENDZ tokens now on: * https://www.nullheroes.io * * - OpenSea is already approved for transactions to spare gas fees * - NullHeroes and related staking contracts are optimized for low gas fees, * at least as much as I could :) * * made with love by [email protected] * special credits: NuclearNerds, WolfGame * */ import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/security/Pausable.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "./ERC721Enumerable.sol"; import "./LEGENDZ.sol"; error NonExistentToken(); error LevelMax(); error TooMuchTokensPerTx(); error NotEnoughTokens(); error NotEnoughGiveaways(); error SaleNotStarted(); error NotEnoughEther(); error NotEnoughLegendz(); contract NullHeroes is ERC721Enumerable, Ownable, Pausable { // hero struct struct Hero { uint8 level; uint8 class; uint8 race; uint8 force; uint8 intelligence; uint8 agility; } // max heroes uint256 public constant MAX_TOKENS = 40000; // genesis heroes (25% of max heroes) uint256 public constant MAX_GENESIS_TOKENS = 10000; // giveaways (5% of genesis heroes) uint256 public constant MAX_GENESIS_TOKENS_GIVEAWAYS = 500; // max per tx uint256 public constant MAX_TOKENS_PER_TX = 10; uint256 public MINT_GENESIS_PRICE = .06942 ether; uint256 public MINT_PRICE = 70000; // giveaways counter uint256 public giveawayGenesisTokens; // $LEGENDZ token contract LEGENDZ private legendz; // pre-generated list of traits distributed by weight uint8[][3] private traits; // mapping from tokenId to a struct containing the token's traits mapping(uint256 => Hero) public heroes; // mapping from proxy address to authorization mapping(address => bool) private proxies; address private proxyRegistryAddress; address private accountingAddress; string private baseURI; constructor( string memory _baseURI, address _proxyRegistryAddress, address _accountingAddress, address _legendz ) ERC721("NullHeroes","NULLHEROES") { baseURI = _baseURI; proxyRegistryAddress = _proxyRegistryAddress; accountingAddress = _accountingAddress; legendz = LEGENDZ(_legendz); // classes - warrior: 0 | rogue: 1 | wizard: 2 | cultist: 3 | mercenary: 4 | ranger: 5 traits[0] = [1, 5, 3, 2, 4, 0]; // races - human: 0 | orc: 1 | elf: 2 | undead: 3 | ape: 4 | human: 5 traits[1] = [5, 0, 1, 3, 5, 0, 1, 4, 1, 5, 2, 0, 3, 0, 1, 5]; // base attribute points - 1 to 6 traits[2] = [1, 2, 3, 2, 2, 5, 1, 3, 2, 4, 1, 1, 2, 2, 3, 2, 5, 3, 6, 2, 2, 4, 3, 1, 3, 1, 4, 1, 1, 2, 1, 4, 2, 1, 3, 1, 2, 1, 2, 1, 1]; } /** * mints genesis heroes for the sender * @param amount the amount of heroes to mint */ function enrollGenesisHeroes(uint256 amount) external payable whenNotPaused { uint256 totalSupply = _owners.length; if (totalSupply >= MAX_GENESIS_TOKENS) revert NotEnoughTokens(); if (amount > MAX_TOKENS_PER_TX) revert TooMuchTokensPerTx(); if (msg.value < MINT_GENESIS_PRICE * amount) revert NotEnoughEther(); uint256 seed = _random(totalSupply); for (uint i; i < amount; i++) { heroes[i + totalSupply] = _generate(seed >> i, true); _mint(_msgSender(), i + totalSupply); } } /** * mints heroes for the sender * @param amount the amount of heroes to mint */ function enrollHeroes(uint256 amount) external whenNotPaused { uint256 totalSupply = _owners.length; if (totalSupply < MAX_GENESIS_TOKENS) revert SaleNotStarted(); if (totalSupply + amount > MAX_TOKENS) revert NotEnoughTokens(); if (amount > MAX_TOKENS_PER_TX) revert TooMuchTokensPerTx(); // check $LEGENDZ balance uint balance = legendz.balanceOf(_msgSender()); uint cost = MINT_PRICE * amount; if (cost > balance) revert NotEnoughLegendz(); // burn $LEGENDZ legendz.burn(_msgSender(), cost); uint256 seed = _random(totalSupply); for (uint i; i < amount; i++) { heroes[i + totalSupply] = _generate(seed >> i, false); _mint(_msgSender(), i + totalSupply); } } /** * mints free genesis heroes for a community member * @param amount the amount of genesis heroes to mint * @param recipient address of the recipient */ function enrollGenesisHeroesForGiveaway(address recipient, uint256 amount) external onlyOwner whenNotPaused { uint256 totalSupply = _owners.length; if (totalSupply >= MAX_GENESIS_TOKENS) revert NotEnoughTokens(); if (amount > MAX_TOKENS_PER_TX) revert TooMuchTokensPerTx(); if (giveawayGenesisTokens + amount > MAX_GENESIS_TOKENS_GIVEAWAYS) revert NotEnoughGiveaways(); giveawayGenesisTokens += amount; uint256 seed = _random(totalSupply); for (uint i; i < amount; i++) { heroes[i + totalSupply] = _generate(seed >> i, true); _mint(recipient, i + totalSupply); } } /** * generates a hero * @param seed a seed * @param isGenesis genesis flag */ function _generate(uint256 seed, bool isGenesis) private view returns (Hero memory h) { h.level = 1; h.class = _selectTrait(uint16(seed), 0); seed >>= 16; h.race = _selectTrait(uint16(seed), 1); seed >>= 16; h.force = _selectTrait(uint16(seed), 2); seed >>= 16; h.intelligence = _selectTrait(uint16(seed), 2); seed >>= 16; h.agility = _selectTrait(uint16(seed), 2); // add race modifiers if (h.race == 0 || h.race == 5) { // human h.force += 2; h.intelligence += 2; h.agility += 2; } else if (h.race == 1) { // orc h.force += 4; h.agility += 2; } else if (h.race == 3) { // undead h.force += 7; h.intelligence += 3; } else if (h.race == 2) { // elf h.force += 3; h.intelligence += 7; h.agility += 7; } else if (h.race == 4) { // ape h.force += 9; h.intelligence -= 1; h.agility += 9; } // add class modifiers if (h.class == 0) { // warrior h.force += 9; } else if (h.class == 1) { // rogue h.force += 3; h.agility += 7; } else if (h.class == 2) { // wizard h.agility += 4; h.force += 1; h.intelligence += 6; } else if (h.class == 3) { // cultist h.intelligence += 9; } else if (h.class == 4) { // mercenary h.force += 4; h.intelligence += 4; h.agility += 4; } else if (h.class == 5) { // ranger h.intelligence += 3; h.agility += 7; } // add genesis modifier if (isGenesis) { h.force += 1; h.agility += 1; h.intelligence += 1; } } /** * selects a random trait * @param seed portion of the 256 bit seed * @param traitType the trait type * @return the index of the randomly selected trait */ function _selectTrait(uint256 seed, uint256 traitType) private view returns (uint8) { if (seed < traits[traitType].length) return traits[traitType][seed]; return traits[traitType][seed % traits[traitType].length]; } /** * generates a pseudorandom number * @param seed a value ensure different outcomes for different sources in the same block * @return a pseudorandom value */ function _random(uint256 seed) private view returns (uint256) { return uint256(keccak256(abi.encodePacked( tx.origin, blockhash(block.number - 1), block.timestamp, seed ))); } function _mint(address to, uint256 tokenId) internal virtual override { _owners.push(to); emit Transfer(address(0), to, tokenId); } /** * transfers an array of tokens * @param _from the current owner * @param _to the new owner * @param _tokenIds the array of token ids */ function batchTransferFrom(address _from, address _to, uint256[] calldata _tokenIds) public { for (uint i; i < _tokenIds.length; i++) { transferFrom(_from, _to, _tokenIds[i]); } } /** * transfers an array of tokens * @param _from the current owner * @param _to the new owner * @param _tokenIds the ids of the tokens * @param _data the transfer data */ function batchSafeTransferFrom(address _from, address _to, uint256[] calldata _tokenIds, bytes memory _data) public { for (uint i; i < _tokenIds.length; i++) { safeTransferFrom(_from, _to, _tokenIds[i], _data); } } /** * level up a hero * @param tokenId the id of the token * @param attribute the attribute to update - force: 0 | intelligence: 1 | agility: 2 */ function levelUp(uint256 tokenId, uint8 attribute) external { if (!proxies[_msgSender()]) revert OnlyAuthorizedOperators(); if (!_exists(tokenId)) revert NonExistentToken(); if (heroes[tokenId].level > 99) revert LevelMax(); heroes[tokenId].level += 1; if (attribute == 0) heroes[tokenId].force += 1; else if (attribute == 1) heroes[tokenId].intelligence += 1; else if (attribute == 2) heroes[tokenId].agility += 1; } /** * gets a hero token * @param tokenId the id of the token * @return a hero struct */ function getHero(uint256 tokenId) public view returns (Hero memory) { if (!_exists(tokenId)) revert NonExistentToken(); return heroes[tokenId]; } /** * gets the tokens of an owner * @param owner owner's address * @return an array of the corresponding owner's token ids */ function tokensOfOwner(address owner) public view returns(uint256[] memory) { uint256 tokenCount = balanceOf(owner); if (tokenCount == 0) return new uint256[](0); uint256[] memory tokensIds = new uint256[](tokenCount); for (uint i; i < tokenCount; i++) { tokensIds[i] = tokenOfOwnerByIndex(owner, i); } return tokensIds; } function tokenURI(uint256 tokenId) public view override returns (string memory) { if (!_exists(tokenId)) revert NonExistentToken(); return string(abi.encodePacked(baseURI, Strings.toString(tokenId))); } function contractURI() public view returns (string memory) { return baseURI; } /** * updates base URI * @param _baseURI the new base URI */ function setBaseURI(string memory _baseURI) external onlyOwner { baseURI = _baseURI; } /** * updates proxy registry address * @param _proxyRegistryAddress proxy registry address */ function setProxyRegistryAddress(address _proxyRegistryAddress) external onlyOwner { proxyRegistryAddress = _proxyRegistryAddress; } /** * sets a proxy's authorization * @param proxyAddress address of the proxy * @param authorized the new authorization value */ function setProxy(address proxyAddress, bool authorized) external onlyOwner { proxies[proxyAddress] = authorized; } /** * burns a token * @param tokenId the id of the token */ function burn(uint256 tokenId) public { require(_isApprovedOrOwner(_msgSender(), tokenId), "not approved to burn"); _burn(tokenId); } /** * withdraws from contract's balance */ function withdraw() public onlyOwner { (bool success, ) = accountingAddress.call{value: address(this).balance}(""); require(success, "failed to send balance"); } /** * enables the contract's owner to pause / unpause minting * @param paused the new pause flag */ function setPaused(bool paused) external onlyOwner { if (paused) _pause(); else _unpause(); } /** * updates the genesis mint price * @param price new price */ function updateGenesisMintPrice(uint256 price) external onlyOwner { MINT_GENESIS_PRICE = price; } /** * updates the mint price * @param price new price */ function updateMintPrice(uint256 price) external onlyOwner { MINT_PRICE = price; } /** * overrides approvals to avoid opensea and operator contracts to generate approval gas fees * @param _owner the current owner * @param _operator the operator */ function isApprovedForAll(address _owner, address _operator) public view override returns (bool) { OpenSeaProxyRegistry proxyRegistry = OpenSeaProxyRegistry(proxyRegistryAddress); if (address(proxyRegistry.proxies(_owner)) == _operator || proxies[_operator]) return true; return super.isApprovedForAll(_owner, _operator); } } contract OwnableDelegateProxy { } contract OpenSeaProxyRegistry { mapping(address => OwnableDelegateProxy) public proxies; } // SPDX-License-Identifier: MIT LICENSE pragma solidity ^0.8.11; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; error OnlyAuthorizedOperators(); error OwnerAuthorizationLocked(); contract LEGENDZ is ERC20, Ownable { // mapping from address to whether or not it can mint / burn mapping(address => bool) proxies; constructor() ERC20("Legendz", "$LEGENDZ") { proxies[_msgSender()] = true; } /** * mints $LEGENDZ to a recipient * @param to the recipient of the $LEGENDZ * @param amount the amount of $LEGENDZ to mint */ function mint(address to, uint256 amount) external { if (!proxies[_msgSender()]) revert OnlyAuthorizedOperators(); _mint(to, amount); } /** * burns $LEGENDZ of a holder * @param from the holder of the $LEGENDZ * @param amount the amount of $LEGENDZ to burn */ function burn(address from, uint256 amount) external { if (!proxies[_msgSender()]) revert OnlyAuthorizedOperators(); _burn(from, amount); } /** * sets a proxy's authorization * @param proxyAddress address of the proxy * @param authorized the new authorization value */ function setProxy(address proxyAddress, bool authorized) public onlyOwner { if (proxyAddress == owner()) revert OwnerAuthorizationLocked(); proxies[proxyAddress] = authorized; } } // SPDX-License-Identifier: MIT LICENSE pragma solidity ^0.8.11; import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/security/Pausable.sol"; import "@openzeppelin/contracts/utils/math/Math.sol"; import "./LEGENDZ.sol"; import "./NullHeroes.sol"; error CannotSendDirectly(); error ZeroAddress(); error NotOwnedToken(); error TooEarlyToClaim(); abstract contract HeroStakes is Ownable, IERC721Receiver, Pausable { // Stake struct struct Stake { address owner; uint256 lastClaim; } // max per transaction uint8 public immutable maxTokensPerTx; // stakes Stake[40000] public stakes; // $LEGENDZ contract LEGENDZ internal legendz; // NullHeroes contract NullHeroes internal nullHeroes; // lock-up period uint256 public minDaysToClaim; constructor(address _legendz, address _nullHeroes, uint8 _maxTokensPerTx) { legendz = LEGENDZ(_legendz); nullHeroes = NullHeroes(_nullHeroes); maxTokensPerTx = _maxTokensPerTx + 1; } /** * stakes some heroes * @param _tokenIds an array of tokenIds to stake */ function stakeHeroes(uint256[] calldata _tokenIds) external virtual whenNotPaused { if (_tokenIds.length > maxTokensPerTx) revert TooMuchTokensPerTx(); nullHeroes.batchTransferFrom(_msgSender(), address(this), _tokenIds); for (uint i; i < _tokenIds.length; i++) { Stake storage stake = stakes[_tokenIds[i]]; stake.owner = _msgSender(); stake.lastClaim = block.timestamp; } } /** * claims the reward of some heroes * @param _tokenIds an array of tokenIds to claim reward from */ function claimReward(uint256[] calldata _tokenIds) external virtual whenNotPaused { if (_tokenIds.length > maxTokensPerTx) revert TooMuchTokensPerTx(); uint256 reward; for (uint i; i < _tokenIds.length; i++) { Stake storage stake = stakes[_tokenIds[i]]; if (stake.owner != _msgSender()) revert NotOwnedToken(); if ((block.timestamp - stake.lastClaim) < minDaysToClaim) revert TooEarlyToClaim(); // resolves reward reward += _resolveReward(_tokenIds[i]); // reset last claim stake.lastClaim = block.timestamp; } if (reward > 0) legendz.mint(_msgSender(), reward); } /** * claims some heroes reward and unstake * @param _tokenIds an array of tokenIds to claim reward from */ function unstakeHeroes(uint256[] calldata _tokenIds) external virtual { if (_tokenIds.length > maxTokensPerTx) revert TooMuchTokensPerTx(); uint256 reward; for (uint i; i < _tokenIds.length; i++) { Stake storage stake = stakes[_tokenIds[i]]; if (stake.owner != _msgSender()) revert NotOwnedToken(); if ((block.timestamp - stake.lastClaim) < minDaysToClaim) revert TooEarlyToClaim(); // resolves reward if not paused if (!paused()) reward += _resolveReward(_tokenIds[i]); delete stakes[_tokenIds[i]]; } if (reward > 0) legendz.mint(_msgSender(), reward); nullHeroes.batchTransferFrom(address(this), _msgSender(), _tokenIds); } /** * resolves a staked hero's total reward * @param _tokenId the hero's tokenId * return the total reward in $LEGENDZ */ function _resolveReward(uint256 _tokenId) internal virtual returns (uint256); /** * estimates a staked hero's total reward * @param _tokenId the hero's tokenId * return the estimated total reward in $LEGENDZ */ function estimateReward(uint256 _tokenId) public view virtual returns (uint256); /** * estimates an unknown hero's approximative daily reward * @return the estimated reward */ function estimateDailyReward() public view virtual returns (uint256); /** * estimates a hero's daily reward * @return the reward */ function estimateDailyReward(uint256 _tokenId) public view virtual returns (uint256); /** * calculates a base reward out of the last claim timestamp and a daily rate * @param _dailyReward the legendz rate per day * @param _lastClaim the amount of days of farming * @return the total reward in $LEGENDZ */ function _calculateBaseReward(uint256 _lastClaim, uint256 _dailyReward) internal view returns (uint256) { return (block.timestamp - _lastClaim) * _dailyReward / 1 days; } function tokensOfOwner(address _owner) public view returns (uint256[] memory) { uint256 tokenCount = _balanceOf(_owner); if (tokenCount == 0) return new uint256[](0); uint256[] memory tokenIds = new uint256[](tokenCount); uint256 index; for (uint i; i < stakes.length; i++) { if (stakes[i].owner == _owner){ tokenIds[index++] = i; if (index == tokenCount) return tokenIds; } } revert("HeroStakes: missing tokens"); } /** * counts the number of tokens staked by an owner * @param _owner the owner * return the token count */ function _balanceOf(address _owner) internal view returns (uint) { if(_owner == address(0)) revert ZeroAddress(); uint count; for (uint i; i < stakes.length; ++i) { if( _owner == stakes[i].owner ) ++count; } return count; } /** * enables owner to pause / unpause staking * @param _paused the new contract paused state */ function setPaused(bool _paused) external onlyOwner { if (_paused) _pause(); else _unpause(); } function onERC721Received( address, address from, uint256, bytes calldata ) external pure override returns (bytes4) { if(from != address(0x0)) revert CannotSendDirectly(); return IERC721Receiver.onERC721Received.selector; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.11; import "./ERC721.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol"; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account but rips out the core of the gas-wasting processing that comes from OpenZeppelin. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { /** * @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-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _owners.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < _owners.length, "ERC721Enumerable: global index out of bounds"); return index; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256 tokenId) { require(index < balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); uint count; for (uint i; i < _owners.length; i++) { if (owner == _owners[i]) { if(count == index) return i; else count++; } } revert("ERC721Enumerable: owner index out of bounds"); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.11; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol"; import "@openzeppelin/contracts/utils/Context.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "@openzeppelin/contracts/utils/introspection/ERC165.sol"; import "./Address.sol"; abstract contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; string private _name; string private _symbol; // Mapping from token ID to owner address address[] internal _owners; mapping(uint256 => address) private _tokenApprovals; 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 (uint) { require(owner != address(0), "ERC721: balance query for the zero address"); uint count; for (uint i; i < _owners.length; ++i) { if( owner == _owners[i] ) ++count; } return count; } /** * @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 {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 tokenId < _owners.length && _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); _owners.push(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); _owners[tokenId] = address(0); 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); _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received( _msgSender(), from, tokenId, _data ) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert( "ERC721: transfer to non ERC721Receiver implementer" ); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.11; library Address { function isContract(address account) internal view returns (bool) { uint size; assembly { size := extcodesize(account) } return size > 0; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/math/Math.sol) pragma solidity ^0.8.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow. return (a & b) + (a ^ b) / 2; } /** * @dev Returns the ceiling of the division of two numbers. * * This differs from standard division with `/` in that it rounds up instead * of rounding down. */ function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b - 1) / b can overflow on addition, so we distribute. return a / b + (a % b == 0 ? 0 : 1); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol) pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol) pragma solidity ^0.8.0; import "../IERC20.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `from` to `to` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/ERC20.sol) pragma solidity ^0.8.0; import "./IERC20.sol"; import "./extensions/IERC20Metadata.sol"; import "../../utils/Context.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `to` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address to, uint256 amount) public virtual override returns (bool) { address owner = _msgSender(); _transfer(owner, to, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on * `transferFrom`. This is semantically equivalent to an infinite approval. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { address owner = _msgSender(); _approve(owner, spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * NOTE: Does not update the allowance if the current allowance * is the maximum `uint256`. * * Requirements: * * - `from` and `to` cannot be the zero address. * - `from` must have a balance of at least `amount`. * - the caller must have allowance for ``from``'s tokens of at least * `amount`. */ function transferFrom( address from, address to, uint256 amount ) public virtual override returns (bool) { address spender = _msgSender(); _spendAllowance(from, spender, amount); _transfer(from, to, amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { address owner = _msgSender(); _approve(owner, spender, _allowances[owner][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { address owner = _msgSender(); uint256 currentAllowance = _allowances[owner][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(owner, spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `from` must have a balance of at least `amount`. */ function _transfer( address from, address to, uint256 amount ) internal virtual { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(from, to, amount); uint256 fromBalance = _balances[from]; require(fromBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[from] = fromBalance - amount; } _balances[to] += amount; emit Transfer(from, to, amount); _afterTokenTransfer(from, to, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Spend `amount` form the allowance of `owner` toward `spender`. * * Does not update the allowance amount in case of infinite allowance. * Revert if not enough allowance is available. * * Might emit an {Approval} event. */ function _spendAllowance( address owner, address spender, uint256 amount ) internal virtual { uint256 currentAllowance = allowance(owner, spender); if (currentAllowance != type(uint256).max) { require(currentAllowance >= amount, "ERC20: insufficient allowance"); unchecked { _approve(owner, spender, currentAllowance - amount); } } } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/Pausable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } }
giveaways (5% of genesis heroes)
uint256 public constant MAX_GENESIS_TOKENS_GIVEAWAYS = 500;
1,206,728
[ 1, 75, 688, 69, 3052, 261, 25, 9, 434, 21906, 366, 2439, 281, 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, 2254, 5034, 1071, 5381, 4552, 67, 16652, 41, 15664, 67, 8412, 55, 67, 43, 5354, 12999, 5255, 55, 273, 6604, 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 ]
./full_match/5/0x87F6eAa56609F0c1977bD3b48D2F35093f162513/sources/src/proxy/HoprStakingProxyForNetworkRegistry.sol
* @dev Remove one matching record from list of special NFTs @param nftType Type index of the special HoprBoost NFT @param nftRank HoprBoost rank which is associated to the special NFT, in string/ walk through overwrite with the last element in the array
function _removeSpecialNftTypeAndRank(uint256 nftType, string memory nftRank) private { for (uint256 i = 0; i < specialNftTypeAndRank.length; i++) { if ( specialNftTypeAndRank[i].nftType == nftType && keccak256(bytes(specialNftTypeAndRank[i].nftRank)) == keccak256(bytes(nftRank)) ) { specialNftTypeAndRank[i] = specialNftTypeAndRank[specialNftTypeAndRank.length - 1]; specialNftTypeAndRank.pop(); maxRegistrationsPerSpecialNft[i] = maxRegistrationsPerSpecialNft[maxRegistrationsPerSpecialNft.length - 1]; maxRegistrationsPerSpecialNft.pop(); emit SpecialNftTypeAndRankRemoved(nftType, nftRank); return; } } }
1,951,398
[ 1, 3288, 1245, 3607, 1409, 628, 666, 434, 4582, 423, 4464, 87, 225, 290, 1222, 559, 1412, 770, 434, 326, 4582, 670, 556, 86, 26653, 423, 4464, 225, 290, 1222, 12925, 670, 556, 86, 26653, 6171, 1492, 353, 3627, 358, 326, 4582, 423, 4464, 16, 316, 533, 19, 5442, 3059, 6156, 598, 326, 1142, 930, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 225, 445, 389, 4479, 12193, 50, 1222, 559, 1876, 12925, 12, 11890, 5034, 290, 1222, 559, 16, 533, 3778, 290, 1222, 12925, 13, 3238, 288, 203, 565, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 4582, 50, 1222, 559, 1876, 12925, 18, 2469, 31, 277, 27245, 288, 203, 1377, 309, 261, 203, 3639, 4582, 50, 1222, 559, 1876, 12925, 63, 77, 8009, 82, 1222, 559, 422, 290, 1222, 559, 597, 203, 3639, 417, 24410, 581, 5034, 12, 3890, 12, 9371, 50, 1222, 559, 1876, 12925, 63, 77, 8009, 82, 1222, 12925, 3719, 422, 417, 24410, 581, 5034, 12, 3890, 12, 82, 1222, 12925, 3719, 203, 1377, 262, 288, 203, 3639, 4582, 50, 1222, 559, 1876, 12925, 63, 77, 65, 273, 4582, 50, 1222, 559, 1876, 12925, 63, 9371, 50, 1222, 559, 1876, 12925, 18, 2469, 300, 404, 15533, 203, 3639, 4582, 50, 1222, 559, 1876, 12925, 18, 5120, 5621, 203, 3639, 943, 20175, 1012, 2173, 12193, 50, 1222, 63, 77, 65, 273, 943, 20175, 1012, 2173, 12193, 50, 1222, 63, 1896, 20175, 1012, 2173, 12193, 50, 1222, 18, 2469, 300, 404, 15533, 203, 3639, 943, 20175, 1012, 2173, 12193, 50, 1222, 18, 5120, 5621, 203, 3639, 3626, 13409, 50, 1222, 559, 1876, 12925, 10026, 12, 82, 1222, 559, 16, 290, 1222, 12925, 1769, 203, 3639, 327, 31, 203, 1377, 289, 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 ]
./full_match/43114/0x1f48dCbCE7fC91180492a7b083472924b4e8a44b/sources/UniswapV2Callee.sol
Convert gem amount to token precision Exit collateral to token version Although Uniswap will accept all gems, this check is a sanity check, just in case Transfer any lingering gem to specified address
function clipperCall( ) external { ( ) = abi.decode(data, (address, address, uint256, address[])); gemAmt = _fromWad(gemJoin, gemAmt); GemJoinLike(gemJoin).exit(address(this), gemAmt); { VaultLike vault = GemJoinLike(gemJoin).gem(); VaultLike bridge = bridges[vault]; if (bridge != VaultLike(0)) { vault.approve(address(bridge), gemAmt); bridge.withdraw(gemAmt, 1); vault.withdraw(gemAmt, 1, true); } } gemAmt = gem.balanceOf(address(this)); gem.approve(address(uniRouter02), gemAmt); gemAmt, 0, path, address(this), block.timestamp ); if (gem.balanceOf(address(this)) > 0) { gem.transfer(to, gem.balanceOf(address(this))); } TokenLike stable = TokenLike(path[path.length - 1]); uint256 amountOut = stable.balanceOf(address(this)); TokenLike psmgem = GemJoinLike(dssPsm.gemJoin()).gem(); if (stable != psmgem) { stable.approve(address(psmgem), amountOut); VaultLike(address(psmgem)).deposit(amountOut); } psmgem.approve(dssPsm.gemJoin(), amountOut); dssPsm.sellGem(address(this), amountOut); require( dai.balanceOf(address(this)) >= add(daiToJoin, minProfit), "UniswapV2Callee/insufficient-profit" ); }
4,567,171
[ 1, 2723, 17474, 3844, 358, 1147, 6039, 9500, 4508, 2045, 287, 358, 1147, 1177, 2262, 18897, 1351, 291, 91, 438, 903, 2791, 777, 314, 7424, 16, 333, 866, 353, 279, 16267, 866, 16, 2537, 316, 648, 12279, 1281, 328, 6658, 310, 17474, 358, 1269, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 565, 445, 6807, 457, 1477, 12, 203, 565, 262, 3903, 288, 203, 3639, 261, 203, 3639, 262, 273, 24126, 18, 3922, 12, 892, 16, 261, 2867, 16, 1758, 16, 2254, 5034, 16, 1758, 63, 5717, 1769, 203, 203, 3639, 17474, 31787, 273, 389, 2080, 59, 361, 12, 23465, 4572, 16, 17474, 31787, 1769, 203, 203, 3639, 611, 351, 4572, 8804, 12, 23465, 4572, 2934, 8593, 12, 2867, 12, 2211, 3631, 17474, 31787, 1769, 203, 203, 3639, 288, 203, 5411, 17329, 8804, 9229, 273, 611, 351, 4572, 8804, 12, 23465, 4572, 2934, 23465, 5621, 203, 5411, 17329, 8804, 10105, 273, 324, 1691, 2852, 63, 26983, 15533, 203, 5411, 309, 261, 18337, 480, 17329, 8804, 12, 20, 3719, 288, 203, 7734, 9229, 18, 12908, 537, 12, 2867, 12, 18337, 3631, 17474, 31787, 1769, 203, 7734, 10105, 18, 1918, 9446, 12, 23465, 31787, 16, 404, 1769, 203, 7734, 9229, 18, 1918, 9446, 12, 23465, 31787, 16, 404, 16, 638, 1769, 203, 5411, 289, 203, 3639, 289, 203, 203, 3639, 17474, 31787, 273, 17474, 18, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 3639, 17474, 18, 12908, 537, 12, 2867, 12, 318, 77, 8259, 3103, 3631, 17474, 31787, 1769, 203, 203, 203, 5411, 17474, 31787, 16, 203, 5411, 374, 16, 203, 5411, 589, 16, 203, 5411, 1758, 12, 2211, 3631, 203, 5411, 1203, 18, 5508, 203, 3639, 11272, 203, 203, 3639, 309, 261, 23465, 18, 12296, 951, 12, 2867, 12, 2211, 3719, 405, 374, 13, 288, 203, 5411, 17474, 18, 13866, 12, 869, 16, 17474, 18, 12296, 951, 2 ]
./full_match/1/0x35CB0fE6f49932A44f39934F47298E6D34680628/sources/contracts/pool/PoolMetadata.sol
@notice Function returns timestamp when pool entered warning utilization state (0 if didn't enter) @return Timestamp of entering warning utilization
function enteredProvisionalDefault() external view returns (uint256) { return _accrueInterestVirtual().enteredProvisionalDefault; }
17,111,269
[ 1, 2083, 1135, 2858, 1347, 2845, 16219, 3436, 1709, 1588, 919, 261, 20, 309, 10242, 1404, 6103, 13, 327, 8159, 434, 19014, 3436, 1709, 1588, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 16219, 9679, 287, 1868, 1435, 3903, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 565, 327, 389, 8981, 86, 344, 29281, 6466, 7675, 2328, 329, 9679, 287, 1868, 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 ]
./partial_match/1/0x21d929770398DF5146346390D2973BF3f30b7684/sources/contracts/LiquidSteak.sol
@notice Sets the Flashtronaut NFT address (which give auction discounts) @dev this can only be called by the Owner
function setFlashtronautNFTAddress(address _newFlashtronautNFTAddress) external onlyOwner { flashtronautNFTAddress = _newFlashtronautNFTAddress; }
15,765,888
[ 1, 2785, 326, 15014, 313, 265, 5854, 423, 4464, 1758, 261, 12784, 8492, 279, 4062, 1015, 8008, 13, 225, 333, 848, 1338, 506, 2566, 635, 326, 16837, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 27059, 313, 265, 5854, 50, 4464, 1887, 12, 2867, 389, 2704, 11353, 313, 265, 5854, 50, 4464, 1887, 13, 3903, 1338, 5541, 288, 203, 3639, 9563, 313, 265, 5854, 50, 4464, 1887, 273, 389, 2704, 11353, 313, 265, 5854, 50, 4464, 1887, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT // File: @openzeppelin/contracts/utils/introspection/IERC165.sol pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: @openzeppelin/contracts/utils/Strings.sol pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File: @openzeppelin/contracts/utils/Context.sol pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: @openzeppelin/contracts/token/ERC721/ERC721.sol pragma solidity ^0.8.0; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // File: @openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol pragma solidity ^0.8.0; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // File: @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); } } pragma solidity >=0.7.0 <0.9.0; contract ApeDrinkClub is ERC721Enumerable, Ownable { using Strings for uint256; string private baseURI; // Definir un días antes de la revelación string public baseExtension = ".json"; uint256 public cost1 = 0.07 ether; //Precio por unidad al comprar 1 o más de 3 uint256 public cost2 = 0.06 ether; //Precio por unidad al comprar 2 uint256 public cost3 = 0.05 ether; //Precio por unidad al comprar 3 uint256 public maxSupply = 10000; // Tokens totales de la colección uint256 public maxMintAmount = 21; // Máxima cantidad máxima mints por usuario uint256 public maxMintTran = 3; // Cantidad máxima minsts por transacción uint64 public ConsumidoWL = 0; uint64 public PorConsumirWL = 0; uint64 public EnWhiteList = 0; bool public paused = true; // Pausa contrato bool public revealed = false; string public notRevealedUri; // Dirección de tonken incógnito mapping(address => bool) private freelistedAddresses; // One free list mapping(address => bool) private WhiteList; // Lista para preventa constructor( string memory _name, string memory _symbol, string memory _initBaseURI, string memory _initNotRevealedUri ) ERC721(_name, _symbol) { setBaseURI(_initBaseURI); setNotRevealedURI(_initNotRevealedUri); } // internal function _baseURI() internal view virtual override returns (string memory) { return baseURI; } /* *Comprobado no es necesario método de añadir individual gestiona bien duplicados, si lo agregas por segunda vez no duplica ni suma otro PorConsumirWL, solo resetea a true lo que haría que pueda tomar otro */ function addOneFreeList(address[] memory _addressToWhitelist) public onlyOwner { for (uint64 i = 0 ; i < _addressToWhitelist.length ; i++) { if(!freelistedAddresses[_addressToWhitelist[i]]) //si ya tiene uno no suma { freelistedAddresses[_addressToWhitelist[i]] = true; PorConsumirWL++; } } } /* Añadir wallet o lista de wallets a la white list */ function addToWhiteList(address[] memory _addressToWhitelist) public onlyOwner { for (uint64 i = 0 ; i < _addressToWhitelist.length ; i++) { if(!WhiteList[_addressToWhitelist[i]]) //si ya tiene uno no suma { WhiteList[_addressToWhitelist[i]] = true; EnWhiteList++; } } } // Setear estado de wallet en white list (False: Deshabilitado ) ALERTA, solo usar para setear FALSE, daña global EnWhiteList function UpdateUserWhiteList(address _whitelistedAddress, bool NewStatus) public onlyOwner { WhiteList[_whitelistedAddress] = NewStatus; if(!NewStatus){EnWhiteList--;} } // Comprar mint desde el white list function WhiteListMint(uint256 _mintAmount) public payable { uint256 supply = totalSupply(); require(_mintAmount > 0); require(PorConsumirWL + supply + _mintAmount <= maxSupply, "Purchase would exceed max supply of Drinks"); //añadir aquí los pendientes por canjear del whiteList if (msg.sender != owner()) { require(_mintAmount <= maxMintTran,"Max: 3 mints each transaction"); // Nos aseguramos que no se produzca un Gas alto require(balanceOf(msg.sender)+_mintAmount<=maxMintAmount , "Max: 21 mints each wallet"); //Nos aseguramos que no puedan tener más de 9 mints require(WhiteList[msg.sender], "This account is not on the white list"); if(_mintAmount == 1) { require(msg.value >= cost1 * _mintAmount, "Ether value sent is not correct"); } else if (_mintAmount == 2) { require(msg.value >= cost2 * _mintAmount, "Ether value sent is not correct"); } else if (_mintAmount == 3) { require(msg.value >= cost3 * _mintAmount, "Ether value sent is not correct"); } else { require(msg.value >= cost1 * _mintAmount, "Ether value sent is not correct"); } } for (uint256 i = 1; i <= _mintAmount; i++) { _safeMint(msg.sender, supply + i); } } /* *Comprobado trata de consumir uno, si se puede setea el address a falso para próxima consumición gratis aumenta los consumidos en 1 y disminuye los por consumir en 1 devuelve canjeado que representa si este usuario puede cobrar su mint */ function TryConsumeOneFree(address _whitelistedAddress) private returns(bool) { bool Canjeado = false; if(freelistedAddresses[_whitelistedAddress]){ require(msg.value < 1, "You have one token free!, enter value 0 to take it"); freelistedAddresses[_whitelistedAddress] = false; Canjeado = true; ConsumidoWL++; PorConsumirWL--; } return Canjeado; } /* Si ya consumión o no está en la lista devuelve true Si no ha consumido (le debemos un token) devuelve falso */ function checkAvaliablePrice(address _whitelistedAddress) public view returns(bool) { return freelistedAddresses[_whitelistedAddress]; } function checkWhiteList(address _whitelistedAddress) public view returns(bool) { return WhiteList[_whitelistedAddress]; } function mintPrize() public payable{ require(TryConsumeOneFree(msg.sender), "No prize to exchange asociated to this wallet"); uint256 supply = totalSupply(); _safeMint(msg.sender, supply + 1); } // public function mint(uint256 _mintAmount) public payable { uint256 supply = totalSupply(); require(!paused, "Error, contrato pausado"); require(_mintAmount > 0); require(PorConsumirWL + supply + _mintAmount <= maxSupply, "Purchase would exceed max supply of Drinks"); //añadir aquí los pendientes por canjear del whiteList require(_mintAmount <= maxMintTran,"Max: 3 mints each transaction"); // Nos aseguramos que no se produzca un Gas alto require(balanceOf(msg.sender)+_mintAmount<=maxMintAmount , "Max: 21 mints each wallet"); //Nos aseguramos que no puedan tener más de 9 mints if(_mintAmount == 1) { require(msg.value >= cost1 * _mintAmount, "Ether value sent is not correct"); } else if (_mintAmount == 2) { require(msg.value >= cost2 * _mintAmount, "Ether value sent is not correct"); } else if (_mintAmount == 3) { require(msg.value >= cost3 * _mintAmount, "Ether value sent is not correct"); } else { require(msg.value >= cost1 * _mintAmount, "Ether value sent is not correct"); } for (uint256 i = 1; i <= _mintAmount; i++) { _safeMint(msg.sender, supply + i); } } //Indica los tokens que posee un wallet function walletOfOwner(address _owner) public view returns (uint256[] memory) { uint256 ownerTokenCount = balanceOf(_owner); uint256[] memory tokenIds = new uint256[](ownerTokenCount); for (uint256 i; i < ownerTokenCount; i++) { tokenIds[i] = tokenOfOwnerByIndex(_owner, i); } return tokenIds; } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId),"ERC721Metadata: URI query for nonexistent token"); if(revealed == false) { return notRevealedUri; } string memory currentBaseURI = _baseURI(); return bytes(currentBaseURI).length > 0 ? string(abi.encodePacked(currentBaseURI, tokenId.toString(), baseExtension)) : ""; } //only owner function reveal() public onlyOwner { revealed = true; } function setCost1(uint256 _newCost) public onlyOwner { cost1 = _newCost; } function setCost2(uint256 _newCost) public onlyOwner { cost2 = _newCost; } function setCost3(uint256 _newCost) public onlyOwner { cost3 = _newCost; } function setmaxMintAmount(uint256 _newmaxMintAmount) public onlyOwner { maxMintAmount = _newmaxMintAmount; } function setNotRevealedURI(string memory _notRevealedURI) public onlyOwner { notRevealedUri = _notRevealedURI; } // Hacer un día antes de la revelación setea BASE URI function setBaseURI(string memory _newBaseURI) public onlyOwner { baseURI = _newBaseURI; } function setBaseExtension(string memory _newBaseExtension) public onlyOwner { baseExtension = _newBaseExtension; } function pause(bool _state) public onlyOwner { paused = _state; } function withdraw() public payable onlyOwner { (bool os, ) = payable(owner()).call{value: address(this).balance}(""); require(os); } }
Cantidad máxima minsts por transacción
uint256 public maxMintTran = 3;
365,533
[ 1, 39, 970, 350, 361, 312, 132, 99, 92, 13888, 225, 1131, 334, 87, 22471, 906, 8981, 77, 132, 116, 82, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 2254, 5034, 1071, 943, 49, 474, 17730, 273, 890, 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 ]
// SPDX-License-Identifier: MIT pragma solidity >=0.4.22 <0.9.0; contract reputationToken { bytes10 public name = "Reputation"; bytes4 public symbol = "REPU"; bytes9 public version = "v1.0.0"; uint256 public granularity = 1; // mapping that stores reputation amount per address mapping(address => uint256) public reputationOf; // stores the standard interactions for modifying reputation mapping(bytes32 => InteractionStandard) public standards; // stores the admin structs which stores if the admin is authorized to issue/burn and also the amount they issued/burned mapping(address => Admin) public admins; // stores the ExternalContract structs which store info on any contracts that are authorized to use specific functions mapping(address => ExternalContract) public contracts; // array of names of InteractionStandards -- for convenience bytes32[] public standardNames; // stores the address of the owner of the smart contract address public owner; // the mapping is there to store any miscellaneous data that may need to be associated with standards in the future struct InteractionStandard { int256 repAmount; // can be negative for negative interactions such as being banned on a forum bool destroyed; // used to indicate if the standard has been "deleted" // mapping(bytes32 => bytes32) misc; // TODO: decide whether this is necessary } // stores admin information struct Admin { bool authorized; uint256 totalRepIssued; uint256 totalRepBurned; } // stores information on an external contract that has the rights to issue and burn reputation struct ExternalContract { bool authorized; bytes32 name; } // regular batching // used when batching multiple single standards/users together struct BatchStandards { address to; bytes32 standardName; } // used in user batching to store the standard names and the number of times that standard should be applied to a user struct StandardCount { bytes32 name; uint count; } // user optimized batching // struct that represents a single user with their address and the standards plus their frequency struct UserBatch { address to; StandardCount[] counts; } // Emitted when the contract generates and assigns and mount of reputation to an account event Issued(address indexed _to, uint256 _amount); // Emitted when the contract burns some amount of reputation on a certain account event Burned(address indexed _from, uint256 _amount); // Emitted when the owner adds an admin event AdminAdded(address indexed _newAdmin); // Emitted when a standard is created, edited, or destroyed event StandardModified(bytes32 indexed _name, int256 _repAmount, bool indexed _destroyed); // Emitted when the owner adds a contract event ContractAdded(address indexed _newContract, bytes32 indexed _name); // BY DEFAULT THESE MODIFIERS GIVE THE OWNER FULL CONTROL // Used to require that the msg.sender (caller) is the controller in order to execute a function modifier onlyAdmin () { require(admins[msg.sender].authorized == true || msg.sender == owner); _; } modifier onlyContract () { require(contracts[msg.sender].authorized == true || msg.sender == owner); _; } modifier onlyOwner () { require(msg.sender == owner); _; } constructor() { // sets the owner as the deployer (who deployed reputationToken and reputationController together) owner = msg.sender; } // function getStandardMisc(bytes32 _name, bytes32 _value) public returns (bytes32) { // return standards[_name].misc[_value]; // } function getStandardNames() public returns (bytes32[] memory){ return standardNames; } // function to issue reputation that can only be used by an authorized external contract function issueReputation(address _to, uint256 _amount) external onlyContract returns (bool success) { reputationOf[_to] += _amount; emit Issued(_to, _amount); return true; } // function to burn reputation that can only be used by an authorized external contract function burnReputation(address _from, uint256 _amount) external onlyContract returns (bool success) { if (reputationOf[_from] - _amount < 0) { reputationOf[_from] = 0; } else { reputationOf[_from] -= _amount; } emit Burned(_from, _amount); return true; } // allows the owner to add an admin but also clear an admins issued/burned counts function addAdmin(address _newAdmin) external onlyOwner returns (bool success) { admins[_newAdmin] = Admin(true, 0, 0); emit AdminAdded(_newAdmin); return true; } // allows the owner to add a contract or change its name function addContract(address _newContractAddr, bytes32 _name) external onlyOwner returns (bool) { contracts[_newContractAddr] = ExternalContract(true, _name); emit ContractAdded(_newContractAddr, _name); return true; } // used to create, edit, or delete any interaction standard function manageStandard(bytes32 _name, int256 _repAmount) external onlyOwner returns (bool success) { // check if _name is in standardNames array -- if it is set nameIndex to the its index in the array uint16 nameIndex = 0; for (uint16 i=0; i < standardNames.length; i++) { if (_name == standardNames[i]) { nameIndex = i + 1; break; } } if (_repAmount != 0) { standards[_name].repAmount = _repAmount; standards[_name].destroyed = false; // if the nameIndex is still 0 then the name is not already in the array if (nameIndex == 0) { standardNames.push(_name); } } else { standards[_name].repAmount = 0; standards[_name].destroyed = true; if (nameIndex > 0) { delete standardNames[nameIndex - 1]; } } emit StandardModified(_name, _repAmount, _repAmount == 0); return true; } // TODO: decide whether to revert or ignore when standard == destroyed or amount is 0 function applySingleStandard(address _to, bytes32 _standardName) public onlyAdmin returns (bool) { int256 amount = standards[_standardName].repAmount; if (amount == 0 || standards[_standardName].destroyed == true) { revert (string(abi.encodePacked( "Cannot apply ", bytes32ToString(_standardName), " to address: ", toString(_to) )) ); } if (amount < 0) { uint256 uAmount = uint256(amount * -1); require(reputationOf[_to] - uAmount >= 0); reputationOf[_to] -= uAmount; admins[msg.sender].totalRepBurned += uAmount; emit Burned(_to, uAmount); } else { reputationOf[_to] += uint256(amount); admins[msg.sender].totalRepIssued += uint256(amount); emit Issued(_to, uint256(amount)); } return true; } // The optimized method of batching by grouping standards under users. The comment below displays what the // format of the data should be. This method allows storing reputation data on a database and periodically updating // the smart contract in order to reduce the total number of transactions. // to: address to give reputation to // counts: array containing the standards (and their amount) to apply to a specific user // name: name of the standard // count: the number of time this standard should be applied for the to address /* [{to:, counts: [{name: "", count: 0}, {name: "", count: 0}]}, {to:, counts: [{name: "", count: 0}, {name: "", count: 0}]}] */ function applyUserBatchStandard(UserBatch[] memory _batch) public onlyAdmin returns (bool) { // loop through the users for (uint256 i=0; i < _batch.length; i++) { int256 total; UserBatch memory user = _batch[i]; StandardCount memory currentStandard; InteractionStandard memory storedStandard; bytes32 name; // loop through the standards to apply to each user for (uint256 j=0; j < user.counts.length; j++) { currentStandard = user.counts[j]; storedStandard = standards[currentStandard.name]; if (storedStandard.repAmount == 0 || storedStandard.destroyed == true) continue; total += storedStandard.repAmount * int256(currentStandard.count); } if (total < 0) { if (reputationOf[user.to] - uint256(total * -1) >= 0) { reputationOf[user.to] -= uint256(total * -1); } else { reputationOf[user.to] = 0; } } else if (total > 0) { reputationOf[user.to] += uint256(total); } } return true; } function applyBatchStandard(BatchStandards[] memory _batch) public onlyAdmin returns (bool) { // return bytesToBytes32(_batch[0].standardName, 0); for (uint256 i=0; i < _batch.length; i++) { applySingleStandard(_batch[i].to, _batch[i].standardName); } return true; } // TODO: devise method for transferring all reputation from one account to another (approval system?) function toString(address account) private pure returns (string memory) { return toString(abi.encodePacked(account)); } function toString(bytes memory data) private pure returns (string memory) { bytes memory alphabet = "0123456789abcdef"; bytes memory str = new bytes(2 + data.length * 2); str[0] = "0"; str[1] = "x"; for (uint i = 0; i < data.length; i++) { str[2+i*2] = alphabet[uint(uint8(data[i] >> 4))]; str[3+i*2] = alphabet[uint(uint8(data[i] & 0x0f))]; } return string(str); } function bytes32ToString(bytes32 _bytes32) private pure returns (string memory) { uint8 i = 0; while(i < 32 && _bytes32[i] != 0) { i++; } bytes memory bytesArray = new bytes(i); for (i = 0; i < 32 && _bytes32[i] != 0; i++) { bytesArray[i] = _bytes32[i]; } return string(bytesArray); } function destroy() public onlyOwner { selfdestruct(payable(owner)); } // receive() external payable {} }
stores information on an external contract that has the rights to issue and burn reputation
struct ExternalContract { bool authorized; bytes32 name; }
12,576,087
[ 1, 19632, 1779, 603, 392, 3903, 6835, 716, 711, 326, 14989, 358, 5672, 471, 18305, 283, 458, 367, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 225, 1958, 11352, 8924, 288, 203, 565, 1426, 10799, 31, 203, 565, 1731, 1578, 508, 31, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.4.25; // https://github.com/ethereum/EIPs/issues/20 interface TRC20 { function totalSupply() external view returns (uint supply); function balanceOf(address _owner) external view returns (uint balance); function transfer(address _to, uint _value) external returns (bool success); function transferFrom(address _from, address _to, uint _value) external returns (bool success); function approve(address _spender, uint _value) external returns (bool success); function allowance(address _owner, address _spender) external view returns (uint remaining); function decimals() external view returns(uint digits); event Approval(address indexed _owner, address indexed _spender, uint _value); } /// @title Reserve contract interface ReserveInterface { function trade( TRC20 srcToken, uint srcAmount, TRC20 destToken, address destAddress, uint conversionRate, uint feeInWei, bool validate ) external payable returns(bool); function getConversionRate(TRC20 src, TRC20 dest, uint srcQty, uint blockNumber) external view returns(uint); } /// @title Kyber Network interface interface NetworkInterface { function maxGasPrice() external view returns(uint); function getUserCapInWei(address user) external view returns(uint); function getUserCapInTokenWei(address user, TRC20 token) external view returns(uint); function enabled() external view returns(bool); function info(bytes32 id) external view returns(uint); function getExpectedRate(TRC20 src, TRC20 dest, uint srcQty) external view returns (uint expectedRate, uint slippageRate); function getExpectedFeeRate(TRC20 token, uint srcQty) external view returns (uint expectedRate, uint slippageRate); function swap(address trader, TRC20 src, uint srcAmount, TRC20 dest, address destAddress, uint maxDestAmount, uint minConversionRate, address walletId) external payable returns(uint); function payTxFee(address trader, TRC20 src, uint srcAmount, address destAddress, uint maxDestAmount, uint minConversionRate) external payable returns(uint); } interface ExpectedRateInterface { function getExpectedRate(TRC20 src, TRC20 dest, uint srcQty) external view returns (uint expectedRate, uint slippageRate); function getExpectedFeeRate(TRC20 token, uint srcQty) external view returns (uint expectedRate, uint slippageRate); } 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; constructor() 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[] memory) { return operatorsGroup; } function getAlerters () external view returns(address[] memory) { 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)); emit 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)); emit TransferAdminPending(newAdmin); emit 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); emit 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); emit 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--; emit 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); emit 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; emit OperatorAdded(operator, false); break; } } } } /** * @title Contracts that should be able to recover tokens or tomos */ contract Withdrawable is PermissionGroups { event TokenWithdraw(TRC20 token, uint amount, address sendTo); /** * @dev Withdraw all TRC20 compatible tokens * @param token TRC20 The address of the token contract */ function withdrawToken(TRC20 token, uint amount, address sendTo) external onlyAdmin { require(token.transfer(sendTo, amount)); emit TokenWithdraw(token, amount, sendTo); } event TomoWithdraw(uint amount, address sendTo); /** * @dev Withdraw Tomos */ function withdrawTomo(uint amount, address sendTo) external onlyAdmin { sendTo.transfer(amount); emit TomoWithdraw(amount, sendTo); } } contract WhiteListInterface { function getUserCapInWei(address user) external view returns (uint userCapWei); } /// @title constants contract contract Utils { TRC20 constant internal TOMO_TOKEN_ADDRESS = TRC20(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 TOMO uint constant internal MAX_DECIMALS = 18; uint constant internal TOMO_DECIMALS = 18; mapping(address=>uint) internal decimals; function setDecimals(TRC20 token) internal { if (token == TOMO_TOKEN_ADDRESS) decimals[token] = TOMO_DECIMALS; else decimals[token] = token.decimals(); } function getDecimals(TRC20 token) internal view returns(uint) { if (token == TOMO_TOKEN_ADDRESS) return TOMO_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 } } contract Utils2 is Utils { /// @dev get the balance of a user. /// @param token The token type /// @return The balance function getBalance(TRC20 token, address user) public view returns(uint) { if (token == TOMO_TOKEN_ADDRESS) return user.balance; else return token.balanceOf(user); } function getDecimalsSafe(TRC20 token) internal returns(uint) { if (decimals[token] == 0) { setDecimals(token); } return decimals[token]; } function calcDestAmount(TRC20 src, TRC20 dest, uint srcAmount, uint rate) internal view returns(uint) { return calcDstQty(srcAmount, getDecimals(src), getDecimals(dest), rate); } function calcSrcAmount(TRC20 src, TRC20 dest, uint destAmount, uint rate) internal view returns(uint) { return calcSrcQty(destAmount, getDecimals(src), getDecimals(dest), rate); } function calcRateFromQty(uint srcAmount, uint destAmount, uint srcDecimals, uint dstDecimals) internal pure returns(uint) { require(srcAmount <= MAX_QTY); require(destAmount <= MAX_QTY); if (dstDecimals >= srcDecimals) { require((dstDecimals - srcDecimals) <= MAX_DECIMALS); return (destAmount * PRECISION / ((10 ** (dstDecimals - srcDecimals)) * srcAmount)); } else { require((srcDecimals - dstDecimals) <= MAX_DECIMALS); return (destAmount * PRECISION * (10 ** (srcDecimals - dstDecimals)) / srcAmount); } } } /// @title Network interface interface NetworkProxyInterface { function maxGasPrice() external view returns(uint); function getUserCapInWei(address user) external view returns(uint); function getUserCapInTokenWei(address user, TRC20 token) external view returns(uint); function enabled() external view returns(bool); function info(bytes32 id) external view returns(uint); function getExpectedRate(TRC20 src, TRC20 dest, uint srcQty) external view returns (uint expectedRate, uint slippageRate); function getExpectedFeeRate(TRC20 token, uint srcQty) external view returns (uint expectedRate, uint slippageRate); function swap(TRC20 src, uint srcAmount, TRC20 dest, address destAddress, uint maxDestAmount, uint minConversionRate, address walletId) external payable returns(uint); function payTxFee(TRC20 src, uint srcAmount, address destAddress, uint maxDestAmount, uint minConversionRate) external payable returns(uint); } /// @title simple interface for Network interface SimpleNetworkInterface { function swapTokenToToken(TRC20 src, uint srcAmount, TRC20 dest, uint minConversionRate) external returns(uint); function swapTomoToToken(TRC20 token, uint minConversionRate) external payable returns(uint); function swapTokenToTomo(TRC20 token, uint srcAmount, uint minConversionRate) external returns(uint); } //////////////////////////////////////////////////////////////////////////////////////////////////////// /// @title Network proxy for main contract contract NetworkProxy is NetworkProxyInterface, SimpleNetworkInterface, Withdrawable, Utils2 { NetworkInterface public networkContract; mapping(address=>bool) public payFeeCallers; constructor(address _admin) public { require(_admin != address(0)); admin = _admin; } /// @notice use token address TOMO_TOKEN_ADDRESS for TOMO /// @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( TRC20 src, uint srcAmount, TRC20 dest, address destAddress, uint maxDestAmount, uint minConversionRate, address walletId ) public payable returns(uint) { return swap( src, srcAmount, dest, destAddress, maxDestAmount, minConversionRate, walletId ); } event AddPayFeeCaller(address caller, bool add); function addPayFeeCaller(address caller, bool add) public onlyAdmin { if (add) { require(payFeeCallers[caller] == false); payFeeCallers[caller] = true; } else { require(payFeeCallers[caller] == true); payFeeCallers[caller] = false; } emit AddPayFeeCaller(caller, add); } /// @notice use token address TOMO_TOKEN_ADDRESS for TOMO /// @dev makes a trade for transaction fee /// @param src Src token /// @param srcAmount amount of src tokens /// @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. /// @return amount of actual dest tokens function payTxFee( TRC20 src, uint srcAmount, address destAddress, uint maxDestAmount, uint minConversionRate ) public payable returns(uint) { require(src == TOMO_TOKEN_ADDRESS || msg.value == 0); require(payFeeCallers[msg.sender] == true, "payTxFee: Sender is not callable this function"); TRC20 dest = TOMO_TOKEN_ADDRESS; UserBalance memory userBalanceBefore; userBalanceBefore.srcBalance = getBalance(src, msg.sender); userBalanceBefore.destBalance = getBalance(dest, destAddress); if (src == TOMO_TOKEN_ADDRESS) { userBalanceBefore.srcBalance += msg.value; } else { require(src.transferFrom(msg.sender, networkContract, srcAmount), "payTxFee: Transer token to network contract"); } uint reportedDestAmount = networkContract.payTxFee.value(msg.value)( msg.sender, src, srcAmount, destAddress, maxDestAmount, minConversionRate ); TradeOutcome memory tradeOutcome = calculateTradeOutcome( userBalanceBefore.srcBalance, userBalanceBefore.destBalance, src, dest, destAddress ); require(reportedDestAmount == tradeOutcome.userDeltaDestAmount, "Report dest amount is different from user delta dest amount"); require(tradeOutcome.userDeltaDestAmount <= maxDestAmount, "userDetalDestAmount > maxDestAmount"); require(tradeOutcome.actualRate >= minConversionRate, "actualRate < minConversionRate"); emit ExecuteTrade(msg.sender, src, dest, tradeOutcome.userDeltaSrcAmount, tradeOutcome.userDeltaDestAmount); return tradeOutcome.userDeltaDestAmount; } /// @notice use token address TOMO_TOKEN_ADDRESS for TOMO /// @dev makes a trade for transaction fee /// @dev auto set maxDestAmount and minConversionRate /// @param src Src token /// @param srcAmount amount of src tokens /// @param destAddress Address to send tokens to /// @return amount of actual dest tokens function payTxFeeFast(TRC20 src, uint srcAmount, address destAddress) external payable returns(uint) { require(payFeeCallers[msg.sender] == true); payTxFee( src, srcAmount, destAddress, MAX_QTY, 0 ); } /// @dev makes a trade between src and dest token and send dest tokens to msg sender /// @param src Src token /// @param srcAmount amount of src tokens /// @param dest Destination token /// @param minConversionRate The minimal conversion rate. If actual rate is lower, trade is canceled. /// @return amount of actual dest tokens function swapTokenToToken( TRC20 src, uint srcAmount, TRC20 dest, uint minConversionRate ) public returns(uint) { return swap( src, srcAmount, dest, msg.sender, MAX_QTY, minConversionRate, 0 ); } /// @dev makes a trade from Tomo to token. Sends token to msg sender /// @param token Destination token /// @param minConversionRate The minimal conversion rate. If actual rate is lower, trade is canceled. /// @return amount of actual dest tokens function swapTomoToToken(TRC20 token, uint minConversionRate) public payable returns(uint) { return swap( TOMO_TOKEN_ADDRESS, msg.value, token, msg.sender, MAX_QTY, minConversionRate, 0 ); } /// @dev makes a trade from token to Tomo, sends Tomo to msg sender /// @param token Src token /// @param srcAmount amount of src tokens /// @param minConversionRate The minimal conversion rate. If actual rate is lower, trade is canceled. /// @return amount of actual dest tokens function swapTokenToTomo(TRC20 token, uint srcAmount, uint minConversionRate) public returns(uint) { return swap( token, srcAmount, TOMO_TOKEN_ADDRESS, msg.sender, MAX_QTY, minConversionRate, 0 ); } struct UserBalance { uint srcBalance; uint destBalance; } event ExecuteTrade(address indexed trader, TRC20 src, TRC20 dest, uint actualSrcAmount, uint actualDestAmount); /// @notice use token address TOMO_TOKEN_ADDRESS for tomo /// @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 swap( TRC20 src, uint srcAmount, TRC20 dest, address destAddress, uint maxDestAmount, uint minConversionRate, address walletId ) public payable returns(uint) { require(src == TOMO_TOKEN_ADDRESS || msg.value == 0); UserBalance memory userBalanceBefore; userBalanceBefore.srcBalance = getBalance(src, msg.sender); userBalanceBefore.destBalance = getBalance(dest, destAddress); if (src == TOMO_TOKEN_ADDRESS) { userBalanceBefore.srcBalance += msg.value; } else { require(src.transferFrom(msg.sender, networkContract, srcAmount), "swap: Can not transfer token to contract"); } uint reportedDestAmount = networkContract.swap.value(msg.value)( msg.sender, src, srcAmount, dest, destAddress, maxDestAmount, minConversionRate, walletId ); TradeOutcome memory tradeOutcome = calculateTradeOutcome( userBalanceBefore.srcBalance, userBalanceBefore.destBalance, src, dest, destAddress ); require(reportedDestAmount == tradeOutcome.userDeltaDestAmount); require(tradeOutcome.userDeltaDestAmount <= maxDestAmount); require(tradeOutcome.actualRate >= minConversionRate); emit ExecuteTrade(msg.sender, src, dest, tradeOutcome.userDeltaSrcAmount, tradeOutcome.userDeltaDestAmount); return tradeOutcome.userDeltaDestAmount; } event NetworkSet(address newNetworkContract, address oldNetworkContract); function setNetworkContract(NetworkInterface _networkContract) public onlyAdmin { require(_networkContract != address(0)); emit NetworkSet(_networkContract, networkContract); networkContract = _networkContract; } function getExpectedRate(TRC20 src, TRC20 dest, uint srcQty) public view returns(uint expectedRate, uint slippageRate) { return networkContract.getExpectedRate(src, dest, srcQty); } function getExpectedFeeRate(TRC20 token, uint srcQty) public view returns (uint expectedRate, uint slippageRate) { return networkContract.getExpectedFeeRate(token, srcQty); } function getUserCapInWei(address user) public view returns(uint) { return networkContract.getUserCapInWei(user); } function getUserCapInTokenWei(address user, TRC20 token) public view returns(uint) { return networkContract.getUserCapInTokenWei(user, token); } function maxGasPrice() public view returns(uint) { return networkContract.maxGasPrice(); } function enabled() public view returns(bool) { return networkContract.enabled(); } function info(bytes32 field) public view returns(uint) { return networkContract.info(field); } struct TradeOutcome { uint userDeltaSrcAmount; uint userDeltaDestAmount; uint actualRate; } function calculateTradeOutcome (uint srcBalanceBefore, uint destBalanceBefore, TRC20 src, TRC20 dest, address destAddress) internal returns(TradeOutcome memory outcome) { uint userSrcBalanceAfter; uint userDestBalanceAfter; userSrcBalanceAfter = getBalance(src, msg.sender); userDestBalanceAfter = getBalance(dest, destAddress); //protect from underflow require(userDestBalanceAfter > destBalanceBefore, "userDestBalanceAfter <= destBalanceBefore"); require(srcBalanceBefore > userSrcBalanceAfter, "srcBalanceBefore <= userSrcBalanceAfter"); outcome.userDeltaDestAmount = userDestBalanceAfter - destBalanceBefore; outcome.userDeltaSrcAmount = srcBalanceBefore - userSrcBalanceAfter; outcome.actualRate = calcRateFromQty( outcome.userDeltaSrcAmount, outcome.userDeltaDestAmount, getDecimalsSafe(src), getDecimalsSafe(dest) ); } }
@title simple interface for Network
interface SimpleNetworkInterface { function swapTokenToToken(TRC20 src, uint srcAmount, TRC20 dest, uint minConversionRate) external returns(uint); function swapTomoToToken(TRC20 token, uint minConversionRate) external payable returns(uint); function swapTokenToTomo(TRC20 token, uint srcAmount, uint minConversionRate) external returns(uint); }
1,804,197
[ 1, 9647, 1560, 364, 5128, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5831, 4477, 27413, 288, 203, 565, 445, 7720, 1345, 774, 1345, 12, 4349, 39, 3462, 1705, 16, 2254, 1705, 6275, 16, 4235, 39, 3462, 1570, 16, 2254, 1131, 6814, 4727, 13, 3903, 1135, 12, 11890, 1769, 203, 565, 445, 7720, 56, 362, 83, 774, 1345, 12, 4349, 39, 3462, 1147, 16, 2254, 1131, 6814, 4727, 13, 3903, 8843, 429, 1135, 12, 11890, 1769, 203, 565, 445, 7720, 1345, 774, 56, 362, 83, 12, 4349, 39, 3462, 1147, 16, 2254, 1705, 6275, 16, 2254, 1131, 6814, 4727, 13, 3903, 1135, 12, 11890, 1769, 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 ]
pragma solidity >=0.0; import "../Oracles/UltimateOracle.sol"; /// @title Ultimate oracle factory contract - Allows to create ultimate oracle contracts /// @author Stefan George - <stefan@gnosis.pm> contract UltimateOracleFactory { /* * Events */ event UltimateOracleCreation( address indexed creator, UltimateOracle ultimateOracle, Oracle oracle, Token collateralToken, uint8 spreadMultiplier, uint challengePeriod, uint challengeAmount, uint frontRunnerPeriod ); /* * Public functions */ /// @dev Creates a new ultimate Oracle contract /// @param oracle Oracle address /// @param collateralToken Collateral token address /// @param spreadMultiplier Defines the spread as a multiple of the money bet on other outcomes /// @param challengePeriod Time to challenge oracle outcome /// @param challengeAmount Amount to challenge the outcome /// @param frontRunnerPeriod Time to overbid the front-runner /// @return ultimateOracle Oracle contract function createUltimateOracle( Oracle oracle, Token collateralToken, uint8 spreadMultiplier, uint challengePeriod, uint challengeAmount, uint frontRunnerPeriod ) public returns (UltimateOracle ultimateOracle) { ultimateOracle = new UltimateOracle( oracle, collateralToken, spreadMultiplier, challengePeriod, challengeAmount, frontRunnerPeriod ); emit UltimateOracleCreation( msg.sender, ultimateOracle, oracle, collateralToken, spreadMultiplier, challengePeriod, challengeAmount, frontRunnerPeriod ); } }
Events/ Public functions/ @dev Creates a new ultimate Oracle contract @param oracle Oracle address @param collateralToken Collateral token address @param spreadMultiplier Defines the spread as a multiple of the money bet on other outcomes @param challengePeriod Time to challenge oracle outcome @param challengeAmount Amount to challenge the outcome @param frontRunnerPeriod Time to overbid the front-runner @return ultimateOracle Oracle contract
{ ultimateOracle = new UltimateOracle( oracle, collateralToken, spreadMultiplier, challengePeriod, challengeAmount, frontRunnerPeriod ); emit UltimateOracleCreation( msg.sender, ultimateOracle, oracle, collateralToken, spreadMultiplier, challengePeriod, challengeAmount, frontRunnerPeriod ); }
6,363,280
[ 1, 3783, 19, 225, 7224, 4186, 19, 225, 10210, 279, 394, 225, 406, 4988, 28544, 6835, 225, 20865, 28544, 1758, 225, 4508, 2045, 287, 1345, 17596, 2045, 287, 1147, 1758, 225, 15103, 23365, 18003, 281, 326, 15103, 487, 279, 3229, 434, 326, 15601, 2701, 603, 1308, 29867, 225, 12948, 5027, 2647, 358, 12948, 20865, 12884, 225, 12948, 6275, 16811, 358, 12948, 326, 12884, 225, 6641, 9709, 5027, 2647, 358, 1879, 19773, 326, 6641, 17, 18156, 327, 225, 406, 4988, 23601, 28544, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 288, 203, 3639, 225, 406, 4988, 23601, 273, 394, 587, 5618, 4988, 23601, 12, 203, 5411, 20865, 16, 203, 5411, 4508, 2045, 287, 1345, 16, 203, 5411, 15103, 23365, 16, 203, 5411, 12948, 5027, 16, 203, 5411, 12948, 6275, 16, 203, 5411, 6641, 9709, 5027, 203, 3639, 11272, 203, 3639, 3626, 587, 5618, 4988, 23601, 9906, 12, 203, 5411, 1234, 18, 15330, 16, 203, 5411, 225, 406, 4988, 23601, 16, 203, 5411, 20865, 16, 203, 5411, 4508, 2045, 287, 1345, 16, 203, 5411, 15103, 23365, 16, 203, 5411, 12948, 5027, 16, 203, 5411, 12948, 6275, 16, 203, 5411, 6641, 9709, 5027, 203, 3639, 11272, 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 ]
./full_match/1/0x06903cC35c37f90B4A9ef38B0b037262a327F83B/sources/contracts/Packing.sol
@dev This packs inputs into a bytes32 @param a The first type to pack @param b The second type to pack @return retval The packed bytes32
function addressUint96(address a, uint96 b) internal pure returns (bytes32 retval) { }
16,586,328
[ 1, 2503, 2298, 87, 4540, 1368, 279, 1731, 1578, 282, 279, 1377, 1021, 1122, 618, 358, 2298, 282, 324, 1377, 1021, 2205, 618, 358, 2298, 327, 5221, 1021, 12456, 1731, 1578, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1758, 5487, 10525, 12, 2867, 279, 16, 2254, 10525, 324, 13, 2713, 16618, 1135, 261, 3890, 1578, 5221, 13, 288, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/3/0x23A14F4200b1eB8A6dbcdD28a9BE07a978F4712e/sources/scripts/simplecoin.sol
set up a balances mapping a mapping is like hash table, or a dictionary or like a two-column spreadsheet index-> value
contract SimpleCoin is ERC20Interface{ address public owner; uint256 _totalSupply; string private _name; string public _symbol; uint8 public _decimals; mapping(address => uint256) private _balances; constructor() { owner = msg.sender; _symbol = "DigitalCoin"; _name = "Token McTokenFace"; _balances[owner] = _totalSupply; } function balanceOf(address account) public view override returns(uint256) { return _balances[account]; } function name() public view returns(string memory) { return _name; } function symbol() public view returns(string memory) { return _symbol; } function decimals() public view returns(uint256) { return _decimals; } function transfer(address account, uint256 amount) public override returns(bool) { address from = msg.sender; address to = account; _balances[from] = _balances[from] - amount; _balances[to] = _balances[to] + amount; emit Transfer(from, account, amount); return true; } function totalSupply() public view override returns(uint256) { return _totalSupply; } function allowance(address owner_allowance, address spender) public view virtual override returns (uint256) { } function approve(address spender, uint256 amount) public virtual override returns (bool){ return true; } function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool){ return true; } }
8,211,324
[ 1, 542, 731, 279, 324, 26488, 2874, 279, 2874, 353, 3007, 1651, 1014, 16, 578, 279, 3880, 578, 3007, 279, 2795, 17, 2827, 30775, 770, 2122, 460, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 4477, 27055, 353, 4232, 39, 3462, 1358, 95, 203, 203, 565, 1758, 1071, 3410, 31, 203, 565, 2254, 5034, 389, 4963, 3088, 1283, 31, 203, 565, 533, 3238, 389, 529, 31, 203, 565, 533, 1071, 389, 7175, 31, 203, 565, 2254, 28, 1071, 389, 31734, 31, 203, 203, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 3238, 389, 70, 26488, 31, 203, 203, 565, 3885, 1435, 288, 203, 203, 3639, 3410, 273, 1234, 18, 15330, 31, 203, 7010, 203, 3639, 389, 7175, 273, 315, 4907, 7053, 27055, 14432, 203, 3639, 389, 529, 273, 315, 1345, 25891, 1345, 11824, 14432, 203, 203, 3639, 389, 70, 26488, 63, 8443, 65, 273, 389, 4963, 3088, 1283, 31, 203, 565, 289, 203, 203, 565, 445, 11013, 951, 12, 2867, 2236, 13, 1071, 1476, 3849, 1135, 12, 11890, 5034, 13, 288, 203, 3639, 327, 389, 70, 26488, 63, 4631, 15533, 203, 565, 289, 203, 203, 565, 445, 508, 1435, 1071, 1476, 1135, 12, 1080, 3778, 13, 288, 203, 3639, 327, 389, 529, 31, 203, 565, 289, 203, 203, 565, 445, 3273, 1435, 1071, 1476, 1135, 12, 1080, 3778, 13, 288, 203, 3639, 327, 389, 7175, 31, 203, 565, 289, 203, 203, 565, 445, 15105, 1435, 1071, 1476, 1135, 12, 11890, 5034, 13, 288, 203, 3639, 327, 389, 31734, 31, 203, 565, 289, 203, 203, 203, 565, 445, 7412, 12, 2867, 2236, 16, 2254, 5034, 3844, 13, 1071, 3849, 1135, 12, 6430, 13, 288, 203, 3639, 1758, 628, 273, 1234, 18, 15330, 31, 203, 3639, 1758, 358, 273, 2236, 2 ]
/* This file is part of The Colony Network. The Colony Network is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. The Colony Network is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with The Colony Network. If not, see <http://www.gnu.org/licenses/>. */ pragma solidity ^0.4.23; pragma experimental "v0.5.0"; import "./CommonStorage.sol"; import "./CommonAuthority.sol"; import "./IRecovery.sol"; /// @title Used for recovery in both ColonyNetwork and Colony instances /// @notice Implements functions defined in IRecovery interface contract ContractRecovery is CommonStorage { function setStorageSlotRecovery(uint256 _slot, bytes32 _value) public recovery auth { require(_slot != AUTHORITY_SLOT, "colony-common-protected-variable"); require(_slot != OWNER_SLOT, "colony-common-protected-variable"); require(_slot != RESOLVER_SLOT, "colony-common-protected-variable"); // NB. This isn't necessarily a colony - could be ColonyNetwork. But they both have this function, so it's okay. IRecovery(this).checkNotAdditionalProtectedVariable(_slot); // Protect key variables uint64 _recoveryRolesCount = recoveryRolesCount; // Make recovery edit uint x = _slot; bytes32 y = _value; assembly { sstore(x, y) } // Restore key variables recoveryRolesCount = _recoveryRolesCount; // Reset recovery state recoveryMode = true; recoveryApprovalCount = 0; recoveryEditedTimestamp = now; } function isInRecoveryMode() public view returns (bool) { return recoveryMode; } function enterRecoveryMode() public stoppable auth { recoveryMode = true; recoveryApprovalCount = 0; recoveryEditedTimestamp = now; } function approveExitRecovery() public recovery auth { require(recoveryApprovalTimestamps[msg.sender] < recoveryEditedTimestamp, "colony-recovery-approval-already-given"); recoveryApprovalTimestamps[msg.sender] = now; recoveryApprovalCount++; } function exitRecoveryMode() public recovery auth { uint totalAuthorized = recoveryRolesCount; // Don't double count the owner (if set); if (owner != 0x0 && !CommonAuthority(authority).hasUserRole(owner, RECOVERY_ROLE)) { totalAuthorized += 1; } uint numRequired = totalAuthorized / 2 + 1; require(recoveryApprovalCount >= numRequired, "colony-recovery-exit-insufficient-approvals"); recoveryMode = false; } // Can only be called by the owner role. function setRecoveryRole(address _user) public stoppable auth { require(recoveryRolesCount < ~uint64(0), "colony-maximum-num-recovery-roles"); if (!CommonAuthority(authority).hasUserRole(_user, RECOVERY_ROLE)) { CommonAuthority(authority).setUserRole(_user, RECOVERY_ROLE, true); recoveryRolesCount++; } } // Can only be called by the owner role. function removeRecoveryRole(address _user) public stoppable auth { if (CommonAuthority(authority).hasUserRole(_user, RECOVERY_ROLE)) { CommonAuthority(authority).setUserRole(_user, RECOVERY_ROLE, false); recoveryRolesCount--; } } function numRecoveryRoles() public view returns(uint64) { return recoveryRolesCount; } }
Reset recovery state
recoveryMode = true;
7,267,724
[ 1, 7013, 11044, 919, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 11044, 2309, 273, 638, 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 ]
/** *Submitted for verification at Etherscan.io on 2020-10-14 */ /* __ __ ___ _ _ ___ __ __ | \/ | / \ | \| | / \ \ V / | |\/| | | - | | .` | | - | _\_/_ |_|__|_| |_|_| |_|\_| |_|_| _|"""""|_|"""""|_|"""""|_|"""""|_|"""""| "`-0-0-'"`-0-0-'"`-0-0-'"`-0-0-'"`-0-0-' ____ __ __ __ _ / __/__ __ ___ / /_ / / ___ / /_ (_)__ __ _\ \ / // // _ \/ __// _ \/ -_)/ __// / \ \ / /___/ \_, //_//_/\__//_//_/\__/ \__//_/ /_\_\ /___/ * Synthetix: VAMPRewards.sol * * Docs: https://docs.synthetix.io/ * * * MIT License * =========== * * Copyright (c) 2020 Synthetix * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE */ pragma solidity ^0.5.17; /** * @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); } } // 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. * * _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: @openzeppelin/contracts/GSN/Context.sol /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/ownership/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. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { _owner = _msgSender(); emit OwnershipTransferred(address(0), _owner); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return _msgSender() == _owner; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol pragma solidity ^0.5.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ interface IERC20 { function mint(address account, uint amount) external; /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity ^0.5.5; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * This test is non-exhaustive, and there may be false-negatives: during the * execution of a contract's constructor, its address will be reported as * not containing a contract. * * IMPORTANT: It is unsafe to assume that an address for which this * function returns false is an externally-owned account (EOA) and not a * contract. */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } /** * @dev Converts an `address` into `address payable`. Note that this is * simply a type cast: the actual underlying value is not changed. * * _Available since v2.4.0._ */ function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. * * _Available since v2.4.0._ */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } } // File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol pragma solidity ^0.5.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: contracts/IRewardDistributionRecipient.sol pragma solidity ^0.5.0; contract IRewardDistributionRecipient is Ownable { address rewardDistribution = 0x45a6b8BdfC1FAa745720165e0B172A3D6D4EC897; function notifyRewardAmount() external; modifier onlyRewardDistribution() { require(_msgSender() == rewardDistribution, "Caller is not reward distribution"); _; } function setRewardDistribution(address _rewardDistribution) external onlyOwner { rewardDistribution = _rewardDistribution; } } // File: contracts/CurveRewards.sol pragma solidity ^0.5.0; pragma solidity ^0.5.17; contract LPTokenWrapper { using SafeMath for uint256; using SafeERC20 for IERC20; IERC20 public vmana_lp = IERC20(0x826B9ec6D671610395CACD14534056c7D758268A); //vmana_lp mainnet uint256 private _totalSupply; mapping(address => uint256) private _balances; function totalSupply() public view returns (uint256) { return _totalSupply; } function balanceOf(address account) public view returns (uint256) { return _balances[account]; } function stake(uint256 amount) public { _totalSupply = _totalSupply.add(amount); _balances[msg.sender] = _balances[msg.sender].add(amount); vmana_lp.safeTransferFrom(msg.sender, address(this), amount); } function withdraw(uint256 amount) public { _totalSupply = _totalSupply.sub(amount); _balances[msg.sender] = _balances[msg.sender].sub(amount); vmana_lp.safeTransfer(msg.sender, amount); } } contract VMANAVAMPPool is LPTokenWrapper, IRewardDistributionRecipient { IERC20 public vamp = IERC20(0xb2C822a1b923E06Dbd193d2cFc7ad15388EA09DD); //vamp uint256 public DURATION = 7 days; uint256 public initreward = 431533550000000000000000; uint256 public starttime = 1603573200; //1 hour after vmana ends uint256 public periodFinish = 0; uint256 public rewardRate = 0; uint256 public lastUpdateTime; uint256 public rewardPerTokenStored; mapping(address => uint256) public userRewardPerTokenPaid; mapping(address => uint256) public rewards; event RewardAdded(uint256 reward); event Staked(address indexed user, uint256 amount); event Withdrawn(address indexed user, uint256 amount); event RewardPaid(address indexed user, uint256 reward); modifier updateReward(address account) { rewardPerTokenStored = rewardPerToken(); lastUpdateTime = lastTimeRewardApplicable(); if (account != address(0)) { rewards[account] = earned(account); userRewardPerTokenPaid[account] = rewardPerTokenStored; } _; } function lastTimeRewardApplicable() public view returns (uint256) { return Math.min(block.timestamp, periodFinish); } function rewardPerToken() public view returns (uint256) { if (totalSupply() == 0) { return rewardPerTokenStored; } return rewardPerTokenStored.add( lastTimeRewardApplicable() .sub(lastUpdateTime) .mul(rewardRate) .mul(1e18) .div(totalSupply()) ); } function earned(address account) public view returns (uint256) { return balanceOf(account) .mul(rewardPerToken().sub(userRewardPerTokenPaid[account])) .div(1e18) .add(rewards[account]); } // stake visibility is public as overriding LPTokenWrapper's stake() function function stake(uint256 amount) public updateReward(msg.sender) checkStart{ require(amount > 0, "Cannot stake 0"); super.stake(amount); emit Staked(msg.sender, amount); } function withdraw(uint256 amount) public updateReward(msg.sender) { require(amount > 0, "Cannot withdraw 0"); super.withdraw(amount); emit Withdrawn(msg.sender, amount); } function exit() external { withdraw(balanceOf(msg.sender)); getReward(); } function getReward() public updateReward(msg.sender) { uint256 reward = earned(msg.sender); if (reward > 0) { rewards[msg.sender] = 0; vamp.safeTransfer(msg.sender, reward); emit RewardPaid(msg.sender, reward); } } function afterEnd() public onlyRewardDistribution { //if any tokens left, transfer to contract owner for further distriubtion to community require(block.timestamp > periodFinish); vamp.safeTransfer(msg.sender,vamp.balanceOf(address(this))); } modifier checkStart(){ require(block.timestamp > starttime,"not start"); _; } function notifyRewardAmount() external onlyRewardDistribution updateReward(address(0)) { if (block.timestamp >= periodFinish) { rewardRate = initreward.div(DURATION); } else { uint256 remaining = periodFinish.sub(block.timestamp); uint256 leftover = remaining.mul(rewardRate); rewardRate = initreward.add(leftover).div(DURATION); } //vamp.mint(address(this),initreward); lastUpdateTime = block.timestamp; periodFinish = starttime.add(DURATION); emit RewardAdded(initreward); } }
1 hour after vmana ends
uint256 public starttime = 1603573200;
2,338,465
[ 1, 21, 6126, 1839, 4268, 13848, 3930, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 5034, 1071, 23437, 273, 2872, 4630, 10321, 1578, 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, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2021-07-02 */ // SPDX-License-Identifier: MIT pragma solidity =0.7.6; pragma experimental ABIEncoderV2; /******************************************************************************\ * Author: Kevin Park, Email: [email protected], Twitter: @tenQkp, Telegram: @freeparkingcapital Discord: tenQ#3843 * www.fruitful.fi * https://twitter.com/FruitfulFi * www.loveboat.exchange * https://twitter.com/LoveBoatDEX * fruitful.eth * Credit: Nick Mudge * * DiamondLove: A multichain decentralized protocol for trading and providing rewards. * * Implementation of an ERC20 governance token that can govern itself and a project * using the Diamond Standard. /******************************************************************************/ /** * @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 addition of two unsigned integers, reverting with custom message on overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, errorMessage); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on underflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot underflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction underflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on underflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot underflow. */ function sub( 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 multiplication of two unsigned integers, reverting on overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul( uint256 a, uint256 b, string memory errorMessage ) 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, errorMessage); return c; } /** * @dev Returns the integer division of two unsigned integers. * Reverts on division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(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; } } library LibGovStorage { struct Voted { uint96 votes; bool support; } struct Proposal { mapping(address => Voted) voted; address proposalContract; address proposer; uint64 endTime; bool executed; bool stuck; uint96 againstVotes; uint96 forVotes; } // How Divisors work: // To get a percentage of a number in Solidity we divide instead of multiply // We get the number to divide to get a percentage of a number with this formula: // divisor = 100 / percentage number // For example let's say we want 25 percent of the number 7808. // First we need to get the divisor so we get it like this: 100 / 25 = 4 // So the divisor is 4. Now we divide 475 by 4 which is 1952 // And that is the answer: 25 percent of 7808 is 1952. struct GovernanceStorage { mapping(address => uint96) balances; mapping(address => mapping(address => uint96)) approved; uint96 totalSupplyCap; uint96 totalSupply; address loveMinter; // The initial account to grant all the tokens address loveBoat; uint256 mintingAllowedAfter; mapping(uint256 => Proposal) proposals; mapping(address => uint24[]) votedProposalIds; uint24 proposalCount; // Proposer must own enough tokens to submit a proposal uint8 proposalThresholdDivisor; // The minimum amount of time a proposal can be voted on. In hours. uint16 minimumVotingTime; // The maximum amount of time a proposal can be voted on. In hours. uint16 maximumVotingTime; // Require an amount of governance tokens for votes to pass a proposal uint8 quorumDivisor; // Proposers get an additional amount of tokens if proposal passes uint8 proposerAwardDivisor; // Voters get an additional amount of tokens for voting on a proposal uint8 voterAwardDivisor; // Cap voter and proposer token awards. // This is to help prevent too much inflation uint8 voteAwardCapDivisor; } function governanceStorage() internal pure returns (GovernanceStorage storage ds) { bytes32 position = keccak256("governance.token.diamond.governance"); assembly { ds.slot := position } } } library LibDiamond { bytes32 internal constant DIAMOND_STORAGE_POSITION = keccak256("diamond.standard.diamond.storage"); struct DiamondStorage { // maps function selectors to the facets that execute the functions. // and maps the selectors to their position in the selectorSlots array. // func selector => address facet, selector position mapping(bytes4 => bytes32) facets; // array of slots of function selectors. // each slot holds 8 function selectors. mapping(uint256 => bytes32) selectorSlots; // The number of function selectors in selectorSlots uint16 selectorCount; // Used to query if a contract implements an interface. // Used to implement ERC-165. mapping(bytes4 => bool) supportedInterfaces; // owner of the contract address contractOwner; } function diamondStorage() internal pure returns (DiamondStorage storage ds) { bytes32 position = DIAMOND_STORAGE_POSITION; assembly { ds.slot := position } } event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); function setContractOwner(address _newOwner) internal { DiamondStorage storage ds = diamondStorage(); address previousOwner = ds.contractOwner; ds.contractOwner = _newOwner; emit OwnershipTransferred(previousOwner, _newOwner); } function contractOwner() internal view returns (address contractOwner_) { contractOwner_ = diamondStorage().contractOwner; } function enforceIsContractOwner() internal view { require(msg.sender == diamondStorage().contractOwner, "LibDiamond: Must be contract owner"); } event DiamondCut(IDiamondCut.FacetCut[] _diamondCut, address _init, bytes _calldata); bytes32 internal constant CLEAR_ADDRESS_MASK = bytes32(uint256(0xffffffffffffffffffffffff)); bytes32 internal constant CLEAR_SELECTOR_MASK = bytes32(uint256(0xffffffff << 224)); // Internal function version of diamondCut // This code is almost the same as the external diamondCut, // except it is using 'Facet[] memory _diamondCut' instead of // 'Facet[] calldata _diamondCut'. // The code is duplicated to prevent copying calldata to memory which // causes an error for a two dimensional array. function diamondCut( IDiamondCut.FacetCut[] memory _diamondCut, address _init, bytes memory _calldata ) internal { DiamondStorage storage ds = diamondStorage(); uint256 originalSelectorCount = ds.selectorCount; uint256 selectorCount = originalSelectorCount; bytes32 selectorSlot; // Check if last selector slot is not full if (selectorCount & 7 > 0) { // get last selectorSlot selectorSlot = ds.selectorSlots[selectorCount >> 3]; } // loop through diamond cut for (uint256 facetIndex; facetIndex < _diamondCut.length; facetIndex++) { (selectorCount, selectorSlot) = addReplaceRemoveFacetSelectors( selectorCount, selectorSlot, _diamondCut[facetIndex].facetAddress, _diamondCut[facetIndex].action, _diamondCut[facetIndex].functionSelectors ); } if (selectorCount != originalSelectorCount) { ds.selectorCount = uint16(selectorCount); } // If last selector slot is not full if (selectorCount & 7 > 0) { ds.selectorSlots[selectorCount >> 3] = selectorSlot; } emit DiamondCut(_diamondCut, _init, _calldata); initializeDiamondCut(_init, _calldata); } function addReplaceRemoveFacetSelectors( uint256 _selectorCount, bytes32 _selectorSlot, address _newFacetAddress, IDiamondCut.FacetCutAction _action, bytes4[] memory _selectors ) internal returns (uint256, bytes32) { DiamondStorage storage ds = diamondStorage(); require(_selectors.length > 0, "LibDiamondCut: No selectors in facet to cut"); if (_action == IDiamondCut.FacetCutAction.Add) { enforceHasContractCode(_newFacetAddress, "LibDiamondCut: Add facet has no code"); for (uint256 selectorIndex; selectorIndex < _selectors.length; selectorIndex++) { bytes4 selector = _selectors[selectorIndex]; bytes32 oldFacet = ds.facets[selector]; require(address(bytes20(oldFacet)) == address(0), "LibDiamondCut: Can't add function that already exists"); // add facet for selector ds.facets[selector] = bytes20(_newFacetAddress) | bytes32(_selectorCount); uint256 selectorInSlotPosition = (_selectorCount & 7) << 5; // clear selector position in slot and add selector _selectorSlot = (_selectorSlot & ~(CLEAR_SELECTOR_MASK >> selectorInSlotPosition)) | (bytes32(selector) >> selectorInSlotPosition); // if slot is full then write it to storage if (selectorInSlotPosition == 224) { ds.selectorSlots[_selectorCount >> 3] = _selectorSlot; _selectorSlot = 0; } _selectorCount++; } } else if (_action == IDiamondCut.FacetCutAction.Replace) { enforceHasContractCode(_newFacetAddress, "LibDiamondCut: Replace facet has no code"); for (uint256 selectorIndex; selectorIndex < _selectors.length; selectorIndex++) { bytes4 selector = _selectors[selectorIndex]; bytes32 oldFacet = ds.facets[selector]; address oldFacetAddress = address(bytes20(oldFacet)); // only useful if immutable functions exist require(oldFacetAddress != address(this), "LibDiamondCut: Can't replace immutable function"); require(oldFacetAddress != _newFacetAddress, "LibDiamondCut: Can't replace function with same function"); require(oldFacetAddress != address(0), "LibDiamondCut: Can't replace function that doesn't exist"); // replace old facet address ds.facets[selector] = (oldFacet & CLEAR_ADDRESS_MASK) | bytes20(_newFacetAddress); } } else if (_action == IDiamondCut.FacetCutAction.Remove) { require(_newFacetAddress == address(0), "LibDiamondCut: Remove facet address must be address(0)"); uint256 selectorSlotCount = _selectorCount >> 3; uint256 selectorInSlotIndex = _selectorCount & 7; for (uint256 selectorIndex; selectorIndex < _selectors.length; selectorIndex++) { if (_selectorSlot == 0) { // get last selectorSlot selectorSlotCount--; _selectorSlot = ds.selectorSlots[selectorSlotCount]; selectorInSlotIndex = 7; } else { selectorInSlotIndex--; } bytes4 lastSelector; uint256 oldSelectorsSlotCount; uint256 oldSelectorInSlotPosition; // adding a block here prevents stack too deep error { bytes4 selector = _selectors[selectorIndex]; bytes32 oldFacet = ds.facets[selector]; require(address(bytes20(oldFacet)) != address(0), "LibDiamondCut: Can't remove function that doesn't exist"); // only useful if immutable functions exist require(address(bytes20(oldFacet)) != address(this), "LibDiamondCut: Can't remove immutable function"); // replace selector with last selector in ds.facets // gets the last selector lastSelector = bytes4(_selectorSlot << (selectorInSlotIndex << 5)); if (lastSelector != selector) { // update last selector slot position info ds.facets[lastSelector] = (oldFacet & CLEAR_ADDRESS_MASK) | bytes20(ds.facets[lastSelector]); } delete ds.facets[selector]; uint256 oldSelectorCount = uint16(uint256(oldFacet)); oldSelectorsSlotCount = oldSelectorCount >> 3; oldSelectorInSlotPosition = (oldSelectorCount & 7) << 5; } if (oldSelectorsSlotCount != selectorSlotCount) { bytes32 oldSelectorSlot = ds.selectorSlots[oldSelectorsSlotCount]; // clears the selector we are deleting and puts the last selector in its place. oldSelectorSlot = (oldSelectorSlot & ~(CLEAR_SELECTOR_MASK >> oldSelectorInSlotPosition)) | (bytes32(lastSelector) >> oldSelectorInSlotPosition); // update storage with the modified slot ds.selectorSlots[oldSelectorsSlotCount] = oldSelectorSlot; } else { // clears the selector we are deleting and puts the last selector in its place. _selectorSlot = (_selectorSlot & ~(CLEAR_SELECTOR_MASK >> oldSelectorInSlotPosition)) | (bytes32(lastSelector) >> oldSelectorInSlotPosition); } if (selectorInSlotIndex == 0) { delete ds.selectorSlots[selectorSlotCount]; _selectorSlot = 0; } } _selectorCount = selectorSlotCount * 8 + selectorInSlotIndex; } else { revert("LibDiamondCut: Incorrect FacetCutAction"); } return (_selectorCount, _selectorSlot); } function initializeDiamondCut(address _init, bytes memory _calldata) internal { if (_init == address(0)) { require(_calldata.length == 0, "LibDiamondCut: _init is address(0) but_calldata is not empty"); } else { require(_calldata.length > 0, "LibDiamondCut: _calldata is empty but _init is not address(0)"); if (_init != address(this)) { enforceHasContractCode(_init, "LibDiamondCut: _init address has no code"); } (bool success, bytes memory error) = _init.delegatecall(_calldata); if (!success) { if (error.length > 0) { // bubble up the error revert(string(error)); } else { revert("LibDiamondCut: _init function reverted"); } } } } function enforceHasContractCode(address _contract, string memory _errorMessage) internal view { uint256 contractSize; assembly { contractSize := extcodesize(_contract) } require(contractSize > 0, _errorMessage); } } // A loupe is a small magnifying glass used to look at diamonds. // These functions look at diamonds interface IDiamondLoupe { /// These functions are expected to be called frequently /// by tools. struct Facet { address facetAddress; bytes4[] functionSelectors; } /// @notice Gets all facet addresses and their four byte function selectors. /// @return facets_ Facet function facets() external view returns (Facet[] memory facets_); /// @notice Gets all the function selectors supported by a specific facet. /// @param _facet The facet address. /// @return facetFunctionSelectors_ function facetFunctionSelectors(address _facet) external view returns (bytes4[] memory facetFunctionSelectors_); /// @notice Get all the facet addresses used by a diamond. /// @return facetAddresses_ function facetAddresses() external view returns (address[] memory facetAddresses_); /// @notice Gets the facet that supports the given selector. /// @dev If facet is not found return address(0). /// @param _functionSelector The function selector. /// @return facetAddress_ The facet address. function facetAddress(bytes4 _functionSelector) external view returns (address facetAddress_); } interface IERC165 { /// @notice Query if a contract implements an interface /// @param interfaceID The interface identifier, as specified in ERC-165 /// @dev Interface identification is specified in ERC-165. This function /// uses less than 30,000 gas. /// @return `true` if the contract implements `interfaceID` and /// `interfaceID` is not 0xffffffff, `false` otherwise function supportsInterface(bytes4 interfaceID) external view returns (bool); } interface IDiamondCut { enum FacetCutAction {Add, Replace, Remove} // Add=0, Replace=1, Remove=2 struct FacetCut { address facetAddress; FacetCutAction action; bytes4[] functionSelectors; } /// @notice Add/replace/remove any number of functions and optionally execute /// a function with delegatecall /// @param _diamondCut Contains the facet addresses and function selectors /// @param _init The address of the contract or facet to execute _calldata /// @param _calldata A function call, including function selector and arguments /// _calldata is executed with delegatecall on _init function diamondCut( FacetCut[] calldata _diamondCut, address _init, bytes calldata _calldata ) external; event DiamondCut(FacetCut[] _diamondCut, address _init, bytes _calldata); } contract DiamondCutFacet is IDiamondCut { /// @notice Add/replace/remove any number of functions and optionally execute /// a function with delegatecall /// @param _diamondCut Contains the facet addresses and function selectors /// @param _init The address of the contract or facet to execute _calldata /// @param _calldata A function call, including function selector and arguments /// _calldata is executed with delegatecall on _init function diamondCut( FacetCut[] calldata _diamondCut, address _init, bytes calldata _calldata ) external override { LibDiamond.enforceIsContractOwner(); LibDiamond.DiamondStorage storage ds = LibDiamond.diamondStorage(); uint256 originalSelectorCount = ds.selectorCount; uint256 selectorCount = originalSelectorCount; bytes32 selectorSlot; // Check if last selector slot is not full if (selectorCount & 7 > 0) { // get last selectorSlot selectorSlot = ds.selectorSlots[selectorCount >> 3]; } // loop through diamond cut for (uint256 facetIndex; facetIndex < _diamondCut.length; facetIndex++) { (selectorCount, selectorSlot) = LibDiamond.addReplaceRemoveFacetSelectors( selectorCount, selectorSlot, _diamondCut[facetIndex].facetAddress, _diamondCut[facetIndex].action, _diamondCut[facetIndex].functionSelectors ); } if (selectorCount != originalSelectorCount) { ds.selectorCount = uint16(selectorCount); } // If last selector slot is not full if (selectorCount & 7 > 0) { ds.selectorSlots[selectorCount >> 3] = selectorSlot; } emit DiamondCut(_diamondCut, _init, _calldata); LibDiamond.initializeDiamondCut(_init, _calldata); } } contract DiamondLoupe is IDiamondLoupe, IERC165 { // Diamond Loupe Functions //////////////////////////////////////////////////////////////////// /// These functions are expected to be called frequently by tools. /// @notice Gets all facets and their selectors. /// @return facets_ Facet function facets() external view override returns (Facet[] memory facets_) { LibDiamond.DiamondStorage storage ds = LibDiamond.diamondStorage(); facets_ = new Facet[](ds.selectorCount); uint8[] memory numFacetSelectors = new uint8[](ds.selectorCount); uint256 numFacets; uint256 selectorIndex; // loop through function selectors for (uint256 slotIndex; selectorIndex < ds.selectorCount; slotIndex++) { bytes32 slot = ds.selectorSlots[slotIndex]; for (uint256 selectorSlotIndex; selectorSlotIndex < 8; selectorSlotIndex++) { selectorIndex++; if (selectorIndex > ds.selectorCount) { break; } bytes4 selector = bytes4(slot << (selectorSlotIndex << 5)); address facetAddress_ = address(bytes20(ds.facets[selector])); bool continueLoop = false; for (uint256 facetIndex; facetIndex < numFacets; facetIndex++) { if (facets_[facetIndex].facetAddress == facetAddress_) { facets_[facetIndex].functionSelectors[numFacetSelectors[facetIndex]] = selector; // probably will never have more than 256 functions from one facet contract require(numFacetSelectors[facetIndex] < 255); numFacetSelectors[facetIndex]++; continueLoop = true; break; } } if (continueLoop) { continueLoop = false; continue; } facets_[numFacets].facetAddress = facetAddress_; facets_[numFacets].functionSelectors = new bytes4[](ds.selectorCount); facets_[numFacets].functionSelectors[0] = selector; numFacetSelectors[numFacets] = 1; numFacets++; } } for (uint256 facetIndex; facetIndex < numFacets; facetIndex++) { uint256 numSelectors = numFacetSelectors[facetIndex]; bytes4[] memory selectors = facets_[facetIndex].functionSelectors; // setting the number of selectors assembly { mstore(selectors, numSelectors) } } // setting the number of facets assembly { mstore(facets_, numFacets) } } /// @notice Gets all the function selectors supported by a specific facet. /// @param _facet The facet address. /// @return _facetFunctionSelectors The selectors associated with a facet address. function facetFunctionSelectors(address _facet) external view override returns (bytes4[] memory _facetFunctionSelectors) { LibDiamond.DiamondStorage storage ds = LibDiamond.diamondStorage(); uint256 numSelectors; _facetFunctionSelectors = new bytes4[](ds.selectorCount); uint256 selectorIndex; // loop through function selectors for (uint256 slotIndex; selectorIndex < ds.selectorCount; slotIndex++) { bytes32 slot = ds.selectorSlots[slotIndex]; for (uint256 selectorSlotIndex; selectorSlotIndex < 8; selectorSlotIndex++) { selectorIndex++; if (selectorIndex > ds.selectorCount) { break; } bytes4 selector = bytes4(slot << (selectorSlotIndex << 5)); address facet = address(bytes20(ds.facets[selector])); if (_facet == facet) { _facetFunctionSelectors[numSelectors] = selector; numSelectors++; } } } // Set the number of selectors in the array assembly { mstore(_facetFunctionSelectors, numSelectors) } } /// @notice Get all the facet addresses used by a diamond. /// @return facetAddresses_ function facetAddresses() external view override returns (address[] memory facetAddresses_) { LibDiamond.DiamondStorage storage ds = LibDiamond.diamondStorage(); facetAddresses_ = new address[](ds.selectorCount); uint256 numFacets; uint256 selectorIndex; // loop through function selectors for (uint256 slotIndex; selectorIndex < ds.selectorCount; slotIndex++) { bytes32 slot = ds.selectorSlots[slotIndex]; for (uint256 selectorSlotIndex; selectorSlotIndex < 8; selectorSlotIndex++) { selectorIndex++; if (selectorIndex > ds.selectorCount) { break; } bytes4 selector = bytes4(slot << (selectorSlotIndex << 5)); address facetAddress_ = address(bytes20(ds.facets[selector])); bool continueLoop = false; for (uint256 facetIndex; facetIndex < numFacets; facetIndex++) { if (facetAddress_ == facetAddresses_[facetIndex]) { continueLoop = true; break; } } if (continueLoop) { continueLoop = false; continue; } facetAddresses_[numFacets] = facetAddress_; numFacets++; } } // Set the number of facet addresses in the array assembly { mstore(facetAddresses_, numFacets) } } /// @notice Gets the facet that supports the given selector. /// @dev If facet is not found return address(0). /// @param _functionSelector The function selector. /// @return facetAddress_ The facet address. function facetAddress(bytes4 _functionSelector) external view override returns (address facetAddress_) { LibDiamond.DiamondStorage storage ds = LibDiamond.diamondStorage(); facetAddress_ = address(bytes20(ds.facets[_functionSelector])); } // This implements ERC-165. function supportsInterface(bytes4 _interfaceId) external view override returns (bool) { LibDiamond.DiamondStorage storage ds = LibDiamond.diamondStorage(); return ds.supportedInterfaces[_interfaceId]; } } contract LoveToken { /** * @dev Returns the name of the token. */ function name() public pure returns (string memory) { return "Love"; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public pure returns (string memory) { return "LOVE"; } /** * @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 pure returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() external view returns (uint256) { return LibGovStorage.governanceStorage().totalSupply; } /** * @notice Get the number of tokens held by the `account` * @param _account The address of the account to get the balance of * @return The number of tokens held */ function balanceOf(address _account) external view returns (uint256) { return LibGovStorage.governanceStorage().balances[_account]; } /// @notice Minimum time between mints uint32 public constant minimumTimeBetweenMints = 1 days * 365; /// @notice Cap on the percentage of totalSupply that can be minted at each mint uint8 public constant mintCap = 2; /// @notice An event thats emitted when the loveMinter address is changed event MinterChanged(address loveMinter, address newMinter); /// @notice The standard EIP-20 transfer event event Transfer(address indexed from, address indexed to, uint256 amount); /// @notice The standard EIP-20 approval event event Approval(address indexed owner, address indexed spender, uint256 amount); function mintingAllowedAfter() public view returns (uint256) { return LibGovStorage.governanceStorage().mintingAllowedAfter; } /** * @notice Change the loveMinter address * @param _loveMinter The address of the new loveMinter */ function setMinter(address _loveMinter) external { require(msg.sender == LibGovStorage.governanceStorage().loveMinter, "Love:setMinter: only the minter can change the minter address"); emit MinterChanged(LibGovStorage.governanceStorage().loveMinter, _loveMinter); LibGovStorage.governanceStorage().loveMinter = _loveMinter; } /** * @notice Mint new tokens * @param _dst The address of the destination account * @param _rawAmount The number of tokens to be minted */ function mint(address _dst, uint256 _rawAmount) external { require(msg.sender == LibGovStorage.governanceStorage().loveMinter, "Love:mint: only the minter can mint"); require(block.timestamp >= LibGovStorage.governanceStorage().mintingAllowedAfter, "Love:mint: minting not allowed yet"); require(_dst != address(0), "Love:mint: cannot transfer to the zero address"); // record the mint LibGovStorage.governanceStorage().mintingAllowedAfter = SafeMath.add(block.timestamp, minimumTimeBetweenMints); // mint the amount uint96 amount = safe96(_rawAmount, "Love:mint: amount exceeds 96 bits"); require( amount <= SafeMath.div(SafeMath.mul(LibGovStorage.governanceStorage().totalSupply, mintCap), 100), "Love:mint: exceeded mint cap" ); LibGovStorage.governanceStorage().totalSupply = safe96( SafeMath.add(LibGovStorage.governanceStorage().totalSupply, amount), "Love:mint: totalSupply exceeds 96 bits" ); // transfer the amount to the recipient LibGovStorage.governanceStorage().balances[_dst] = add96( LibGovStorage.governanceStorage().balances[_dst], amount, "Love:mint: transfer amount overflows" ); emit Transfer(address(0), _dst, amount); } /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param _to The address of the destination account * @param _value The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address _to, uint256 _value) external returns (bool) { uint96 value = safe96(_value, "Love:transfer: value exceeds 96 bits"); _transferFrom(msg.sender, _to, value); return true; } /** * @notice Transfer `amount` tokens from `src` to `dst` * @param _from The address of the source account * @param _to The address of the destination account * @param _rawValue The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom( address _from, address _to, uint256 _rawValue ) external returns (bool) { address spender = msg.sender; uint96 spenderAllowance = LibGovStorage.governanceStorage().approved[_from][spender]; uint96 value = safe96(_rawValue, "Love: value exceeds 96 bits"); if (spender != _from && spenderAllowance != type(uint96).max) { uint96 newSpenderAllowance = sub96(spenderAllowance, value, "Love:transferFrom: value exceeds spenderAllowance"); LibGovStorage.governanceStorage().approved[_from][spender] = newSpenderAllowance; emit Approval(_from, spender, newSpenderAllowance); } _transferFrom(_from, _to, value); return true; } function _transferFrom( address _from, address _to, uint96 _value ) internal { require(_from != address(0), "Love:_transferFrom: transfer from the zero address"); require(_to != address(0), "Love:_transferFrom: transfer to the zero address"); require(_value <= LibGovStorage.governanceStorage().balances[_from], "Love:_transferFrom: transfer amount exceeds balance"); LibGovStorage.governanceStorage().balances[_from] = sub96( LibGovStorage.governanceStorage().balances[_from], _value, "Love:_transferFrom: value exceeds balance" ); LibGovStorage.governanceStorage().balances[_to] = add96( LibGovStorage.governanceStorage().balances[_to], _value, "Love:_transferFrom: value overflows" ); emit Transfer(_from, _to, _value); } /** * @notice Approve `_spender` to transfer up to `_rawValue` from `src` * @dev This will overwrite the approval _rawValue for `_spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param _spender The address of the account which may transfer tokens * @param _rawValue The number of tokens that are approved * returns success whether or not the approval succeeded */ function approve(address _spender, uint256 _rawValue) external returns (bool success) { uint96 value = safe96(_rawValue, "Love: value exceeds 96 bits"); LibGovStorage.governanceStorage().approved[msg.sender][_spender] = value; emit Approval(msg.sender, _spender, value); success = true; } function safe32(uint256 n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function safe96(uint256 n, string memory errorMessage) internal pure returns (uint96) { require(n < 2**96, errorMessage); return uint96(n); } function add96( uint96 a, uint96 b, string memory errorMessage ) internal pure returns (uint96) { uint96 c = a + b; require(c >= a, errorMessage); return c; } function sub96( uint96 a, uint96 b, string memory errorMessage ) internal pure returns (uint96) { require(b <= a, errorMessage); return a - b; } } contract DiamondLove { /// @dev Placing these events here in order to emit the ERC20 standard Transfer event at DiamondLove contract deployment /// @notice An event thats emitted when the loveMinter address is changed event MinterChanged(address loveMinter, address newMinter); /// @notice The standard EIP-20 transfer event event Transfer(address indexed from, address indexed to, uint256 amount); constructor() { LibGovStorage.GovernanceStorage storage gs = LibGovStorage.governanceStorage(); // Set total supply cap. The token supply cannot grow past this. gs.totalSupplyCap = 100_000_000e18; gs.totalSupply = 1_000_000e18; gs.loveMinter = 0x287300059f50850d098b974AbE59106c4F52c989; // Initial address with the permission to mint Love tokens. emit MinterChanged(address(0), gs.loveMinter); gs.loveBoat = 0x287300059f50850d098b974AbE59106c4F52c989; // The address the token genesis minting will be sent to. // No minting is allowed for about a year after the contract is deployed. Only 2% of the total supply can be minted every year. gs.mintingAllowedAfter = block.timestamp + (1 days * 365); // Initially mint tokens to gs.loveBoat. This is the Fruitful Labs EOA. The vesting contract will be deployed on Polygon L2. gs.balances[gs.loveBoat] = gs.totalSupply; emit Transfer(address(0), gs.loveBoat, gs.balances[gs.loveBoat]); // Set DiamondLove contract owner LibDiamond.setContractOwner(0x287300059f50850d098b974AbE59106c4F52c989); // Deploy facets DiamondCutFacet diamondCutFacet = new DiamondCutFacet(); DiamondLoupe diamondLoupe = new DiamondLoupe(); LoveToken loveToken = new LoveToken(); // Create array of facet cuts (DiamondCutFacet, DiamondLoupe, LoveToken) IDiamondCut.FacetCut[] memory cut = new IDiamondCut.FacetCut[](3); // Add DiamondCutFacet bytes4[] memory funcSDiamondCut = new bytes4[](1); funcSDiamondCut[0] = DiamondCutFacet.diamondCut.selector; cut[0] = IDiamondCut.FacetCut(address(diamondCutFacet), IDiamondCut.FacetCutAction.Add, funcSDiamondCut); // Add DiamondLoupe bytes4[] memory funcSDiamondLoupe = new bytes4[](5); funcSDiamondLoupe[0] = IDiamondLoupe.facetFunctionSelectors.selector; funcSDiamondLoupe[1] = IDiamondLoupe.facets.selector; funcSDiamondLoupe[2] = IDiamondLoupe.facetAddress.selector; funcSDiamondLoupe[3] = IDiamondLoupe.facetAddresses.selector; funcSDiamondLoupe[4] = IERC165.supportsInterface.selector; cut[1] = IDiamondCut.FacetCut(address(diamondLoupe), IDiamondCut.FacetCutAction.Add, funcSDiamondLoupe); // Add LoveToken bytes4[] memory funcSLoveToken = new bytes4[](11); funcSLoveToken[0] = LoveToken.name.selector; funcSLoveToken[1] = LoveToken.symbol.selector; funcSLoveToken[2] = LoveToken.decimals.selector; funcSLoveToken[3] = LoveToken.totalSupply.selector; funcSLoveToken[4] = LoveToken.balanceOf.selector; funcSLoveToken[5] = LoveToken.mintingAllowedAfter.selector; funcSLoveToken[6] = LoveToken.setMinter.selector; funcSLoveToken[7] = LoveToken.mint.selector; funcSLoveToken[8] = LoveToken.transfer.selector; funcSLoveToken[9] = LoveToken.transferFrom.selector; funcSLoveToken[10] = LoveToken.approve.selector; cut[2] = IDiamondCut.FacetCut(address(loveToken), IDiamondCut.FacetCutAction.Add, funcSLoveToken); LibDiamond.diamondCut(cut, address(0), new bytes(0)); // adding ERC165 data LibDiamond.DiamondStorage storage ds = LibDiamond.diamondStorage(); ds.supportedInterfaces[type(IERC165).interfaceId] = true; ds.supportedInterfaces[type(IDiamondCut).interfaceId] = true; ds.supportedInterfaces[type(IDiamondLoupe).interfaceId] = true; } // Find facet for function that is called and execute the // function if a facet is found and return any value. fallback() external payable { LibDiamond.DiamondStorage storage ds; bytes32 position = LibDiamond.DIAMOND_STORAGE_POSITION; assembly { ds.slot := position } address facet = address(bytes20(ds.facets[msg.sig])); require(facet != address(0), "DiamondLove: Function does not exist"); assembly { calldatacopy(0, 0, calldatasize()) let result := delegatecall(gas(), facet, 0, calldatasize(), 0, 0) returndatacopy(0, 0, returndatasize()) switch result case 0 { revert(0, returndatasize()) } default { return(0, returndatasize()) } } } receive() external payable {} }
The initial account to grant all the tokens Proposer must own enough tokens to submit a proposal The minimum amount of time a proposal can be voted on. In hours. The maximum amount of time a proposal can be voted on. In hours. Require an amount of governance tokens for votes to pass a proposal Proposers get an additional amount of tokens if proposal passes Voters get an additional amount of tokens for voting on a proposal Cap voter and proposer token awards. This is to help prevent too much inflation
struct GovernanceStorage { mapping(address => uint96) balances; mapping(address => mapping(address => uint96)) approved; uint96 totalSupplyCap; uint96 totalSupply; address loveMinter; address loveBoat; uint256 mintingAllowedAfter; mapping(uint256 => Proposal) proposals; mapping(address => uint24[]) votedProposalIds; uint24 proposalCount; uint8 proposalThresholdDivisor; uint16 minimumVotingTime; uint16 maximumVotingTime; uint8 quorumDivisor; uint8 proposerAwardDivisor; uint8 voterAwardDivisor; uint8 voteAwardCapDivisor; }
7,953,721
[ 1, 1986, 2172, 2236, 358, 7936, 777, 326, 2430, 1186, 5607, 1297, 4953, 7304, 2430, 358, 4879, 279, 14708, 1021, 5224, 3844, 434, 813, 279, 14708, 848, 506, 331, 16474, 603, 18, 657, 7507, 18, 1021, 4207, 3844, 434, 813, 279, 14708, 848, 506, 331, 16474, 603, 18, 657, 7507, 18, 12981, 392, 3844, 434, 314, 1643, 82, 1359, 2430, 364, 19588, 358, 1342, 279, 14708, 1186, 917, 414, 336, 392, 3312, 3844, 434, 2430, 309, 14708, 11656, 776, 352, 414, 336, 392, 3312, 3844, 434, 2430, 364, 331, 17128, 603, 279, 14708, 11200, 331, 20005, 471, 450, 5607, 1147, 279, 6397, 18, 1220, 353, 358, 2809, 5309, 4885, 9816, 13947, 367, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 611, 1643, 82, 1359, 3245, 288, 203, 3639, 2874, 12, 2867, 516, 2254, 10525, 13, 324, 26488, 31, 203, 3639, 2874, 12, 2867, 516, 2874, 12, 2867, 516, 2254, 10525, 3719, 20412, 31, 203, 3639, 2254, 10525, 2078, 3088, 1283, 4664, 31, 203, 3639, 2254, 10525, 2078, 3088, 1283, 31, 203, 3639, 1758, 437, 537, 49, 2761, 31, 203, 3639, 1758, 437, 537, 13809, 270, 31, 203, 3639, 2254, 5034, 312, 474, 310, 5042, 4436, 31, 203, 3639, 2874, 12, 11890, 5034, 516, 19945, 13, 450, 22536, 31, 203, 3639, 2874, 12, 2867, 516, 2254, 3247, 63, 5717, 331, 16474, 14592, 2673, 31, 203, 3639, 2254, 3247, 14708, 1380, 31, 203, 3639, 2254, 28, 14708, 7614, 7244, 12385, 31, 203, 3639, 2254, 2313, 5224, 58, 17128, 950, 31, 203, 3639, 2254, 2313, 4207, 58, 17128, 950, 31, 203, 3639, 2254, 28, 31854, 7244, 12385, 31, 203, 3639, 2254, 28, 450, 5607, 37, 2913, 7244, 12385, 31, 203, 3639, 2254, 28, 331, 20005, 37, 2913, 7244, 12385, 31, 203, 3639, 2254, 28, 12501, 37, 2913, 4664, 7244, 12385, 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 ]
/** *Submitted for verification at Etherscan.io on 2020-09-24 */ pragma solidity ^0.6.6; /** * @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; // } } /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ // function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ // event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ // event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev 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"); // } } /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn( token, abi.encodeWithSelector(token.transfer.selector, to, value) ); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn( token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value) ); } function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn( token, abi.encodeWithSelector(token.approve.selector, spender, value) ); } // function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { // uint256 newAllowance = token.allowance(address(this), spender).add(value); // _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); // } // function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { // uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); // _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); // } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require( abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed" ); } } } /** * @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 _reserve, uint256 _amount, uint256 _fee, bytes calldata _params ) external; } /** @title ILendingPoolAddressesProvider interface @notice provides the interface to fetch the LendingPoolCore address */ interface ILendingPoolAddressesProvider { function getLendingPoolCore() external view returns (address payable); function getLendingPool() external view returns (address); } /* * @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 virtual view 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 Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20MinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ // contract ERC20 is Context, IERC20 { // using SafeMath for uint256; // using Address for address; // mapping (address => uint256) private _balances; // mapping (address => mapping (address => uint256)) private _allowances; // uint256 private _totalSupply; // string private _name; // string private _symbol; // uint8 private _decimals; // /** // * @dev Sets the values for {name} and {symbol}, initializes {decimals} with // * a default value of 18. // * // * To select a different value for {decimals}, use {_setupDecimals}. // * // * All three of these values are immutable: they can only be set once during // * construction. // */ // constructor (string memory name, string memory symbol) public { // _name = name; // _symbol = symbol; // _decimals = 18; // } // /** // * @dev Returns the name of the token. // */ // function name() public view returns (string memory) { // return _name; // } // /** // * @dev Returns the symbol of the token, usually a shorter version of the // * name. // */ // function symbol() public view returns (string memory) { // return _symbol; // } // /** // * @dev Returns the number of decimals used to get its user representation. // * For example, if `decimals` equals `2`, a balance of `505` tokens should // * be displayed to a user as `5,05` (`505 / 10 ** 2`). // * // * Tokens usually opt for a value of 18, imitating the relationship between // * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is // * called. // * // * NOTE: This information is only used for _display_ purposes: it in // * no way affects any of the arithmetic of the contract, including // * {IERC20-balanceOf} and {IERC20-transfer}. // */ // function decimals() public view returns (uint8) { // return _decimals; // } // /** // * @dev See {IERC20-totalSupply}. // */ // function totalSupply() public view override returns (uint256) { // return _totalSupply; // } // /** // * @dev See {IERC20-balanceOf}. // */ // function balanceOf(address account) public view override returns (uint256) { // return _balances[account]; // } // /** // * @dev See {IERC20-transfer}. // * // * Requirements: // * // * - `recipient` cannot be the zero address. // * - the caller must have a balance of at least `amount`. // */ // function transfer(address recipient, uint256 amount) public virtual override returns (bool) { // _transfer(_msgSender(), recipient, amount); // return true; // } // /** // * @dev See {IERC20-allowance}. // */ // function allowance(address owner, address spender) public view virtual override returns (uint256) { // return _allowances[owner][spender]; // } // /** // * @dev See {IERC20-approve}. // * // * Requirements: // * // * - `spender` cannot be the zero address. // */ // function approve(address spender, uint256 amount) public virtual override returns (bool) { // _approve(_msgSender(), spender, amount); // return true; // } // /** // * @dev See {IERC20-transferFrom}. // * // * Emits an {Approval} event indicating the updated allowance. This is not // * required by the EIP. See the note at the beginning of {ERC20}; // * // * Requirements: // * - `sender` and `recipient` cannot be the zero address. // * - `sender` must have a balance of at least `amount`. // * - the caller must have allowance for ``sender``'s tokens of at least // * `amount`. // */ // function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { // _transfer(sender, recipient, amount); // _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); // return true; // } // /** // * @dev Atomically increases the allowance granted to `spender` by the caller. // * // * This is an alternative to {approve} that can be used as a mitigation for // * problems described in {IERC20-approve}. // * // * Emits an {Approval} event indicating the updated allowance. // * // * Requirements: // * // * - `spender` cannot be the zero address. // */ // function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { // _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); // return true; // } // /** // * @dev Atomically decreases the allowance granted to `spender` by the caller. // * // * This is an alternative to {approve} that can be used as a mitigation for // * problems described in {IERC20-approve}. // * // * Emits an {Approval} event indicating the updated allowance. // * // * Requirements: // * // * - `spender` cannot be the zero address. // * - `spender` must have allowance for the caller of at least // * `subtractedValue`. // */ // function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { // _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); // return true; // } // /** // * @dev Moves tokens `amount` from `sender` to `recipient`. // * // * This is internal function is equivalent to {transfer}, and can be used to // * e.g. implement automatic token fees, slashing mechanisms, etc. // * // * Emits a {Transfer} event. // * // * Requirements: // * // * - `sender` cannot be the zero address. // * - `recipient` cannot be the zero address. // * - `sender` must have a balance of at least `amount`. // */ // function _transfer(address sender, address recipient, uint256 amount) internal virtual { // require(sender != address(0), "ERC20: transfer from the zero address"); // require(recipient != address(0), "ERC20: transfer to the zero address"); // _beforeTokenTransfer(sender, recipient, amount); // _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); // _balances[recipient] = _balances[recipient].add(amount); // emit Transfer(sender, recipient, amount); // } // /** @dev Creates `amount` tokens and assigns them to `account`, increasing // * the total supply. // * // * Emits a {Transfer} event with `from` set to the zero address. // * // * Requirements // * // * - `to` cannot be the zero address. // */ // function _mint(address account, uint256 amount) internal virtual { // require(account != address(0), "ERC20: mint to the zero address"); // _beforeTokenTransfer(address(0), account, amount); // _totalSupply = _totalSupply.add(amount); // _balances[account] = _balances[account].add(amount); // emit Transfer(address(0), account, amount); // } // /** // * @dev Destroys `amount` tokens from `account`, reducing the // * total supply. // * // * Emits a {Transfer} event with `to` set to the zero address. // * // * Requirements // * // * - `account` cannot be the zero address. // * - `account` must have at least `amount` tokens. // */ // function _burn(address account, uint256 amount) internal virtual { // require(account != address(0), "ERC20: burn from the zero address"); // _beforeTokenTransfer(account, address(0), amount); // _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); // _totalSupply = _totalSupply.sub(amount); // emit Transfer(account, address(0), amount); // } // /** // * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. // * // * This is internal function is equivalent to `approve`, and can be used to // * e.g. set automatic allowances for certain subsystems, etc. // * // * Emits an {Approval} event. // * // * Requirements: // * // * - `owner` cannot be the zero address. // * - `spender` cannot be the zero address. // */ // function _approve(address owner, address spender, uint256 amount) internal virtual { // require(owner != address(0), "ERC20: approve from the zero address"); // require(spender != address(0), "ERC20: approve to the zero address"); // _allowances[owner][spender] = amount; // emit Approval(owner, spender, amount); // } // /** // * @dev Sets {decimals} to a value other than the default one of 18. // * // * WARNING: This function should only be called from the constructor. Most // * applications that interact with token contracts will not expect // * {decimals} to ever change, and may work incorrectly if it does. // */ // function _setupDecimals(uint8 decimals_) internal { // _decimals = decimals_; // } // /** // * @dev Hook that is called before any transfer of tokens. This includes // * minting and burning. // * // * Calling conditions: // * // * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens // * will be to transferred to `to`. // * - when `from` is zero, `amount` tokens will be minted for `to`. // * - when `to` is zero, `amount` of ``from``'s tokens will be burned. // * - `from` and `to` are never both zero. // * // * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. // */ // function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } // } /** * @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; // } } /** Ensures that any contract that inherits from this contract is able to withdraw funds that are accidentally received or stuck. */ contract Withdrawable is Ownable { using SafeERC20 for IERC20; address constant ETHER = address(0); // event LogWithdraw( // address indexed _from, // address indexed _assetAddress, // uint amount // ); /** * @dev Withdraw asset. * @param _assetAddress Asset to be withdrawn. */ function withdraw(address _assetAddress) public onlyOwner { uint256 assetBalance; if (_assetAddress == ETHER) { address self = address(this); // workaround for a possible solidity bug assetBalance = self.balance; msg.sender.transfer(assetBalance); } else { assetBalance = IERC20(_assetAddress).balanceOf(address(this)); IERC20(_assetAddress).safeTransfer(msg.sender, assetBalance); } // emit LogWithdraw(msg.sender, _assetAddress, assetBalance); } } abstract contract FlashLoanReceiverBase is IFlashLoanReceiver, Withdrawable { using SafeERC20 for IERC20; using SafeMath for uint256; address constant ethAddress = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; ILendingPoolAddressesProvider public addressesProvider; constructor(address _addressProvider) public { addressesProvider = ILendingPoolAddressesProvider(_addressProvider); } receive() external payable {} function transferFundsBackToPoolInternal(address _reserve, uint256 _amount) internal { address payable core = addressesProvider.getLendingPoolCore(); transferInternal(core, _reserve, _amount); } function transferInternal( address payable _destination, address _reserve, uint256 _amount ) internal { if (_reserve == ethAddress) { (bool success, ) = _destination.call{value: _amount}(""); require(success == true, "Couldn't transfer ETH"); return; } IERC20(_reserve).safeTransfer(_destination, _amount); } function getBalanceInternal(address _target, address _reserve) internal view returns (uint256) { if (_reserve == ethAddress) { return _target.balance; } return IERC20(_reserve).balanceOf(_target); } } interface ILendingPool { function addressesProvider() external view returns (address); // function deposit ( address _reserve, uint256 _amount, uint16 _referralCode ) external payable; // function redeemUnderlying ( address _reserve, address _user, uint256 _amount ) external; // function borrow ( address _reserve, uint256 _amount, uint256 _interestRateMode, uint16 _referralCode ) external; // function repay ( address _reserve, uint256 _amount, address _onBehalfOf ) external payable; // function swapBorrowRateMode ( address _reserve ) external; // function rebalanceFixedBorrowRate ( address _reserve, address _user ) external; // function setUserUseReserveAsCollateral ( address _reserve, bool _useAsCollateral ) external; // function liquidationCall ( address _collateral, address _reserve, address _user, uint256 _purchaseAmount, bool _receiveAToken ) external payable; function flashLoan( address _receiver, address _reserve, uint256 _amount, bytes calldata _params ) external; // function getReserveConfigurationData ( address _reserve ) external view returns ( uint256 ltv, uint256 liquidationThreshold, uint256 liquidationDiscount, address interestRateStrategyAddress, bool usageAsCollateralEnabled, bool borrowingEnabled, bool fixedBorrowRateEnabled, bool isActive ); // function getReserveData ( address _reserve ) external view returns ( uint256 totalLiquidity, uint256 availableLiquidity, uint256 totalBorrowsFixed, uint256 totalBorrowsVariable, uint256 liquidityRate, uint256 variableBorrowRate, uint256 fixedBorrowRate, uint256 averageFixedBorrowRate, uint256 utilizationRate, uint256 liquidityIndex, uint256 variableBorrowIndex, address aTokenAddress, uint40 lastUpdateTimestamp ); // function getUserAccountData ( address _user ) external view returns ( uint256 totalLiquidityETH, uint256 totalCollateralETH, uint256 totalBorrowsETH, uint256 availableBorrowsETH, uint256 currentLiquidationThreshold, uint256 ltv, uint256 healthFactor ); // function getUserReserveData ( address _reserve, address _user ) external view returns ( uint256 currentATokenBalance, uint256 currentUnderlyingBalance, uint256 currentBorrowBalance, uint256 principalBorrowBalance, uint256 borrowRateMode, uint256 borrowRate, uint256 liquidityRate, uint256 originationFee, uint256 variableBorrowIndex, uint256 lastUpdateTimestamp, bool usageAsCollateralEnabled ); // function getReserves () external view; } interface IUniswapRouter { function swapExactTokensForTokens( uint256, uint256, address[] calldata, address, uint256 ) external; } interface IBank { function withdraw(address underlying, uint256 withdrawTokens) external; function controller() external view returns (address); function liquidateBorrow( address borrower, address underlyingBorrow, address underlyingCollateral, uint256 repayAmount ) external payable; } interface IFToken { function balanceOf(address account) external view returns (uint256); } interface IBankController { function getFTokeAddress(address underlying) external view returns (address); } contract FlashloanForTube is FlashLoanReceiverBase { using SafeERC20 for IERC20; address public bank = address(0xdE7B3b2Fe0E7b4925107615A5b199a4EB40D9ca9); address[] public reserve2BorrowRouting; address[] public swap2TokenRouting; address public uniRouterV2 = address( 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D ); address public weth = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); // used for for <> weth <> usdc route constructor(address _addressProvider) public FlashLoanReceiverBase(_addressProvider) {} function doApprove(address erc20, address spender) public { IERC20(erc20).safeApprove(spender, 0); IERC20(erc20).safeApprove(spender, uint256(-1)); } /** This function is called after your contract has received the flash loaned amount */ function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params ) external override { require( _amount <= getBalanceInternal(address(this), _reserve), "Invalid balance, was the flashLoan successful?" ); // // Your logic goes here. // !! Ensure that *this contract* has enough of `_reserve` funds to payback the `_fee` !! // ( address borrower, address underlyingBorrow, address underlyingCollateral, uint256 repayAmount ) = abi.decode(_params, (address, address, address, uint256)); if (_reserve != underlyingBorrow) { // reserve2BorrowRouting = [_reserve, weth, underlyingBorrow]; IUniswapRouter(uniRouterV2).swapExactTokensForTokens( IERC20(_reserve).balanceOf(address(this)), 0, reserve2BorrowRouting, address(this), now.add(1800) ); } doApprove(_reserve, bank); IBank(bank).liquidateBorrow( borrower, underlyingBorrow, underlyingCollateral, repayAmount ); IBankController ctrl = IBankController(IBank(bank).controller()); IFToken fToken = IFToken(ctrl.getFTokeAddress(underlyingCollateral)); IBank(bank).withdraw( underlyingCollateral, fToken.balanceOf(address(this)) ); //use uniswap doApprove(underlyingCollateral, uniRouterV2); // swap2TokenRouting = [underlyingCollateral, weth, _reserve]; IUniswapRouter(uniRouterV2).swapExactTokensForTokens( IERC20(underlyingCollateral).balanceOf(address(this)), 0, swap2TokenRouting, address(this), now.add(1800) ); uint256 totalDebt = _amount.add(_fee); transferFundsBackToPoolInternal(_reserve, totalDebt); } /** Flash loan _amount worth of `_asset` with _data */ function flashloan( address _asset, uint256 _amount, bytes calldata _data ) external onlyOwner { ILendingPool lendingPool = ILendingPool( addressesProvider.getLendingPool() ); lendingPool.flashLoan(address(this), _asset, _amount, _data); } function set( address _bank, address _weth, address _uniRouterV2, address _addressesProvider ) external onlyOwner { bank = _bank; weth = _weth; uniRouterV2 = _uniRouterV2; addressesProvider = ILendingPoolAddressesProvider(_addressesProvider); } function setRouting( address[] calldata _reserve2BorrowRouting, address[] calldata _swap2TokenRouting ) external onlyOwner { reserve2BorrowRouting = _reserve2BorrowRouting; swap2TokenRouting = _swap2TokenRouting; } }
*/ Your logic goes here. !! Ensure that *this contract* has enough of `_reserve` funds to payback the `_fee` !! reserve2BorrowRouting = [_reserve, weth, underlyingBorrow];
This function is called after your contract has received the flash loaned amount function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params ) external override { require( _amount <= getBalanceInternal(address(this), _reserve), "Invalid balance, was the flashLoan successful?" ); ( address borrower, address underlyingBorrow, address underlyingCollateral, uint256 repayAmount ) = abi.decode(_params, (address, address, address, uint256)); if (_reserve != underlyingBorrow) { IUniswapRouter(uniRouterV2).swapExactTokensForTokens( IERC20(_reserve).balanceOf(address(this)), 0, reserve2BorrowRouting, address(this), now.add(1800) ); } doApprove(_reserve, bank); IBank(bank).liquidateBorrow( borrower, underlyingBorrow, underlyingCollateral, repayAmount ); IBankController ctrl = IBankController(IBank(bank).controller()); IFToken fToken = IFToken(ctrl.getFTokeAddress(underlyingCollateral)); IBank(bank).withdraw( underlyingCollateral, fToken.balanceOf(address(this)) ); IERC20(underlyingCollateral).balanceOf(address(this)), 0, swap2TokenRouting, address(this), now.add(1800) ); uint256 totalDebt = _amount.add(_fee); transferFundsBackToPoolInternal(_reserve, totalDebt); }
8,061,837
[ 1, 19, 20471, 4058, 13998, 2674, 18, 401, 5, 7693, 716, 333, 6835, 711, 7304, 434, 1375, 67, 455, 6527, 68, 284, 19156, 358, 8843, 823, 326, 1375, 67, 21386, 68, 401, 5, 20501, 22, 38, 15318, 13966, 273, 306, 67, 455, 6527, 16, 341, 546, 16, 6808, 38, 15318, 15533, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 1220, 445, 353, 2566, 1839, 3433, 6835, 711, 5079, 326, 9563, 28183, 329, 3844, 203, 565, 445, 1836, 2988, 12, 203, 3639, 1758, 389, 455, 6527, 16, 203, 3639, 2254, 5034, 389, 8949, 16, 203, 3639, 2254, 5034, 389, 21386, 16, 203, 3639, 1731, 745, 892, 389, 2010, 203, 565, 262, 3903, 3849, 288, 203, 3639, 2583, 12, 203, 5411, 389, 8949, 1648, 2882, 6112, 3061, 12, 2867, 12, 2211, 3631, 389, 455, 6527, 3631, 203, 5411, 315, 1941, 11013, 16, 1703, 326, 9563, 1504, 304, 6873, 7225, 203, 3639, 11272, 203, 203, 203, 3639, 261, 203, 5411, 1758, 29759, 264, 16, 203, 5411, 1758, 6808, 38, 15318, 16, 203, 5411, 1758, 6808, 13535, 2045, 287, 16, 203, 5411, 2254, 5034, 2071, 528, 6275, 203, 3639, 262, 273, 24126, 18, 3922, 24899, 2010, 16, 261, 2867, 16, 1758, 16, 1758, 16, 2254, 5034, 10019, 203, 203, 3639, 309, 261, 67, 455, 6527, 480, 6808, 38, 15318, 13, 288, 203, 5411, 467, 984, 291, 91, 438, 8259, 12, 318, 77, 8259, 58, 22, 2934, 22270, 14332, 5157, 1290, 5157, 12, 203, 7734, 467, 654, 39, 3462, 24899, 455, 6527, 2934, 12296, 951, 12, 2867, 12, 2211, 13, 3631, 203, 7734, 374, 16, 203, 7734, 20501, 22, 38, 15318, 13966, 16, 203, 7734, 1758, 12, 2211, 3631, 203, 7734, 2037, 18, 1289, 12, 2643, 713, 13, 203, 5411, 11272, 203, 3639, 289, 203, 203, 3639, 741, 12053, 537, 24899, 455, 6527, 16, 11218, 1769, 203, 3639, 467, 16040, 12, 10546, 2934, 549, 26595, 340, 38, 2 ]
./full_match/80001/0xb52b844F9c9481Bcb8CdDb44e6E8322267627fb6/sources/circuit_v2/contract/main/plonk_vk.sol
* @notice Verify a Ultra Plonk proof @param _proof - The serialized proof @param _publicInputs - An array of the public inputs @return True if proof is valid, reverts otherwise/* LOAD PROOF FROM CALLDATA/* LOAD RECURSIVE PROOF INTO MEMORY/ validate these are valid bn128 G1 points The public input location is stored at 0x24, we then add 0x24 to skip selector and the length of public inputs copy the public inputs over copy W1, W2, W3 into challenge. Each point is 0x40 bytes, so load 0xc0 = 3 * 0x40 bytes (ETA input length) Challenge is the old challenge + public inputs + W1, W2, W3 (0x20 + public_input_size + 0xc0)* COMPUTE PUBLIC INPUT DELTA ΔPI = ∏ᵢ∈ℓ(wᵢ + β σ(i) + γ) / ∏ᵢ∈ℓ(wᵢ + β σ'(i) + γ)/ Load the starting point of the public inputs (jump over the selector and the length of public inputs [0x24]) endpoint_ptr = public_inputs_ptr + num_inputs * 0x20. every public input is 0x20 bytes root_1 = β * 0x05 root_2 = β * 0x0c @note 0x05 + 0x07 == 0x0c == external coset generator Revert if not all public inputs are field elements (i.e. < p)* Compute Plookup delta factor [γ(1 + β)]^{n-k} k = num roots cut out of Z_H = 4/
function verify(bytes calldata _proof, bytes32[] calldata _publicInputs) external view returns (bool) { loadVerificationKey(N_LOC, OMEGA_INVERSE_LOC); uint256 requiredPublicInputCount; assembly { requiredPublicInputCount := mload(NUM_INPUTS_LOC) } if (requiredPublicInputCount != _publicInputs.length) { revert PUBLIC_INPUT_COUNT_INVALID(requiredPublicInputCount, _publicInputs.length); } assembly { { let data_ptr := add(calldataload(0x04), 0x24) mstore(W1_Y_LOC, mod(calldataload(data_ptr), q)) mstore(W1_X_LOC, mod(calldataload(add(data_ptr, 0x20)), q)) mstore(W2_Y_LOC, mod(calldataload(add(data_ptr, 0x40)), q)) mstore(W2_X_LOC, mod(calldataload(add(data_ptr, 0x60)), q)) mstore(W3_Y_LOC, mod(calldataload(add(data_ptr, 0x80)), q)) mstore(W3_X_LOC, mod(calldataload(add(data_ptr, 0xa0)), q)) mstore(W4_Y_LOC, mod(calldataload(add(data_ptr, 0xc0)), q)) mstore(W4_X_LOC, mod(calldataload(add(data_ptr, 0xe0)), q)) mstore(S_Y_LOC, mod(calldataload(add(data_ptr, 0x100)), q)) mstore(S_X_LOC, mod(calldataload(add(data_ptr, 0x120)), q)) mstore(Z_Y_LOC, mod(calldataload(add(data_ptr, 0x140)), q)) mstore(Z_X_LOC, mod(calldataload(add(data_ptr, 0x160)), q)) mstore(Z_LOOKUP_Y_LOC, mod(calldataload(add(data_ptr, 0x180)), q)) mstore(Z_LOOKUP_X_LOC, mod(calldataload(add(data_ptr, 0x1a0)), q)) mstore(T1_Y_LOC, mod(calldataload(add(data_ptr, 0x1c0)), q)) mstore(T1_X_LOC, mod(calldataload(add(data_ptr, 0x1e0)), q)) mstore(T2_Y_LOC, mod(calldataload(add(data_ptr, 0x200)), q)) mstore(T2_X_LOC, mod(calldataload(add(data_ptr, 0x220)), q)) mstore(T3_Y_LOC, mod(calldataload(add(data_ptr, 0x240)), q)) mstore(T3_X_LOC, mod(calldataload(add(data_ptr, 0x260)), q)) mstore(T4_Y_LOC, mod(calldataload(add(data_ptr, 0x280)), q)) mstore(T4_X_LOC, mod(calldataload(add(data_ptr, 0x2a0)), q)) mstore(W1_EVAL_LOC, mod(calldataload(add(data_ptr, 0x2c0)), p)) mstore(W2_EVAL_LOC, mod(calldataload(add(data_ptr, 0x2e0)), p)) mstore(W3_EVAL_LOC, mod(calldataload(add(data_ptr, 0x300)), p)) mstore(W4_EVAL_LOC, mod(calldataload(add(data_ptr, 0x320)), p)) mstore(S_EVAL_LOC, mod(calldataload(add(data_ptr, 0x340)), p)) mstore(Z_EVAL_LOC, mod(calldataload(add(data_ptr, 0x360)), p)) mstore(Z_LOOKUP_EVAL_LOC, mod(calldataload(add(data_ptr, 0x380)), p)) mstore(Q1_EVAL_LOC, mod(calldataload(add(data_ptr, 0x3a0)), p)) mstore(Q2_EVAL_LOC, mod(calldataload(add(data_ptr, 0x3c0)), p)) mstore(Q3_EVAL_LOC, mod(calldataload(add(data_ptr, 0x3e0)), p)) mstore(Q4_EVAL_LOC, mod(calldataload(add(data_ptr, 0x400)), p)) mstore(QM_EVAL_LOC, mod(calldataload(add(data_ptr, 0x420)), p)) mstore(QC_EVAL_LOC, mod(calldataload(add(data_ptr, 0x440)), p)) mstore(QARITH_EVAL_LOC, mod(calldataload(add(data_ptr, 0x460)), p)) mstore(QSORT_EVAL_LOC, mod(calldataload(add(data_ptr, 0x480)), p)) mstore(QELLIPTIC_EVAL_LOC, mod(calldataload(add(data_ptr, 0x4a0)), p)) mstore(QAUX_EVAL_LOC, mod(calldataload(add(data_ptr, 0x4c0)), p)) mstore(SIGMA1_EVAL_LOC, mod(calldataload(add(data_ptr, 0x4e0)), p)) mstore(SIGMA2_EVAL_LOC, mod(calldataload(add(data_ptr, 0x500)), p)) mstore(SIGMA3_EVAL_LOC, mod(calldataload(add(data_ptr, 0x520)), p)) mstore(SIGMA4_EVAL_LOC, mod(calldataload(add(data_ptr, 0x540)), p)) mstore(TABLE1_EVAL_LOC, mod(calldataload(add(data_ptr, 0x560)), p)) mstore(TABLE2_EVAL_LOC, mod(calldataload(add(data_ptr, 0x580)), p)) mstore(TABLE3_EVAL_LOC, mod(calldataload(add(data_ptr, 0x5a0)), p)) mstore(TABLE4_EVAL_LOC, mod(calldataload(add(data_ptr, 0x5c0)), p)) mstore(TABLE_TYPE_EVAL_LOC, mod(calldataload(add(data_ptr, 0x5e0)), p)) mstore(ID1_EVAL_LOC, mod(calldataload(add(data_ptr, 0x600)), p)) mstore(ID2_EVAL_LOC, mod(calldataload(add(data_ptr, 0x620)), p)) mstore(ID3_EVAL_LOC, mod(calldataload(add(data_ptr, 0x640)), p)) mstore(ID4_EVAL_LOC, mod(calldataload(add(data_ptr, 0x660)), p)) mstore(W1_OMEGA_EVAL_LOC, mod(calldataload(add(data_ptr, 0x680)), p)) mstore(W2_OMEGA_EVAL_LOC, mod(calldataload(add(data_ptr, 0x6a0)), p)) mstore(W3_OMEGA_EVAL_LOC, mod(calldataload(add(data_ptr, 0x6c0)), p)) mstore(W4_OMEGA_EVAL_LOC, mod(calldataload(add(data_ptr, 0x6e0)), p)) mstore(S_OMEGA_EVAL_LOC, mod(calldataload(add(data_ptr, 0x700)), p)) mstore(Z_OMEGA_EVAL_LOC, mod(calldataload(add(data_ptr, 0x720)), p)) mstore(Z_LOOKUP_OMEGA_EVAL_LOC, mod(calldataload(add(data_ptr, 0x740)), p)) mstore(TABLE1_OMEGA_EVAL_LOC, mod(calldataload(add(data_ptr, 0x760)), p)) mstore(TABLE2_OMEGA_EVAL_LOC, mod(calldataload(add(data_ptr, 0x780)), p)) mstore(TABLE3_OMEGA_EVAL_LOC, mod(calldataload(add(data_ptr, 0x7a0)), p)) mstore(TABLE4_OMEGA_EVAL_LOC, mod(calldataload(add(data_ptr, 0x7c0)), p)) mstore(PI_Z_Y_LOC, mod(calldataload(add(data_ptr, 0x7e0)), q)) mstore(PI_Z_X_LOC, mod(calldataload(add(data_ptr, 0x800)), q)) mstore(PI_Z_OMEGA_Y_LOC, mod(calldataload(add(data_ptr, 0x820)), q)) mstore(PI_Z_OMEGA_X_LOC, mod(calldataload(add(data_ptr, 0x840)), q)) } { if mload(CONTAINS_RECURSIVE_PROOF_LOC) { let public_inputs_ptr := add(calldataload(0x24), 0x24) let index_counter := add(shl(5, mload(RECURSIVE_PROOF_PUBLIC_INPUT_INDICES_LOC)), public_inputs_ptr) let x0 := calldataload(index_counter) x0 := add(x0, shl(68, calldataload(add(index_counter, 0x20)))) x0 := add(x0, shl(136, calldataload(add(index_counter, 0x40)))) x0 := add(x0, shl(204, calldataload(add(index_counter, 0x60)))) let y0 := calldataload(add(index_counter, 0x80)) y0 := add(y0, shl(68, calldataload(add(index_counter, 0xa0)))) y0 := add(y0, shl(136, calldataload(add(index_counter, 0xc0)))) y0 := add(y0, shl(204, calldataload(add(index_counter, 0xe0)))) let x1 := calldataload(add(index_counter, 0x100)) x1 := add(x1, shl(68, calldataload(add(index_counter, 0x120)))) x1 := add(x1, shl(136, calldataload(add(index_counter, 0x140)))) x1 := add(x1, shl(204, calldataload(add(index_counter, 0x160)))) let y1 := calldataload(add(index_counter, 0x180)) y1 := add(y1, shl(68, calldataload(add(index_counter, 0x1a0)))) y1 := add(y1, shl(136, calldataload(add(index_counter, 0x1c0)))) y1 := add(y1, shl(204, calldataload(add(index_counter, 0x1e0)))) mstore(RECURSIVE_P1_X_LOC, x0) mstore(RECURSIVE_P1_Y_LOC, y0) mstore(RECURSIVE_P2_X_LOC, x1) mstore(RECURSIVE_P2_Y_LOC, y1) if iszero(and(and(lt(x0, q), lt(x1, q)), and(lt(y0, q), lt(y1, q)))) { mstore(0x00, PUBLIC_INPUT_INVALID_BN128_G1_POINT_SELECTOR) revert(0x00, 0x04) } } } { mstore(0x00, shl(224, mload(N_LOC))) mstore(0x04, shl(224, mload(NUM_INPUTS_LOC))) let challenge := keccak256(0x00, 0x08) mstore(PUBLIC_INPUTS_HASH_LOCATION, challenge) let public_inputs_start := add(calldataload(0x24), 0x24) let public_input_size := mul(mload(NUM_INPUTS_LOC), 0x20) calldatacopy(add(PUBLIC_INPUTS_HASH_LOCATION, 0x20), public_inputs_start, public_input_size) let w_start := add(calldataload(0x04), 0x24) calldatacopy(add(add(PUBLIC_INPUTS_HASH_LOCATION, 0x20), public_input_size), w_start, ETA_INPUT_LENGTH) let challenge_bytes_size := add(0x20, add(public_input_size, ETA_INPUT_LENGTH)) challenge := keccak256(PUBLIC_INPUTS_HASH_LOCATION, challenge_bytes_size) { let eta := mod(challenge, p) mstore(C_ETA_LOC, eta) mstore(C_ETA_SQR_LOC, mulmod(eta, eta, p)) mstore(C_ETA_CUBE_LOC, mulmod(mload(C_ETA_SQR_LOC), eta, p)) } mstore(0x20, mload(W4_Y_LOC)) mstore(0x40, mload(W4_X_LOC)) mstore(0x60, mload(S_Y_LOC)) mstore(0x80, mload(S_X_LOC)) challenge := keccak256(0x00, 0xa0) mstore(C_BETA_LOC, mod(challenge, p)) mstore8(0x20, 0x01) challenge := keccak256(0x00, 0x21) mstore(C_GAMMA_LOC, mod(challenge, p)) mstore(0x20, mload(Z_Y_LOC)) mstore(0x40, mload(Z_X_LOC)) mstore(0x60, mload(Z_LOOKUP_Y_LOC)) mstore(0x80, mload(Z_LOOKUP_X_LOC)) challenge := keccak256(0x00, 0xa0) mstore(C_ALPHA_LOC, mod(challenge, p)) mstore(C_ALPHA_SQR_LOC, mulmod(alpha, alpha, p)) mstore(C_ALPHA_CUBE_LOC, mulmod(mload(C_ALPHA_SQR_LOC), alpha, p)) mstore(C_ALPHA_QUAD_LOC, mulmod(mload(C_ALPHA_CUBE_LOC), alpha, p)) mstore(C_ALPHA_BASE_LOC, alpha) mstore(0x20, mload(T1_Y_LOC)) mstore(0x40, mload(T1_X_LOC)) mstore(0x60, mload(T2_Y_LOC)) mstore(0x80, mload(T2_X_LOC)) mstore(0xa0, mload(T3_Y_LOC)) mstore(0xc0, mload(T3_X_LOC)) mstore(0xe0, mload(T4_Y_LOC)) mstore(0x100, mload(T4_X_LOC)) challenge := keccak256(0x00, 0x120) mstore(C_ZETA_LOC, mod(challenge, p)) mstore(C_CURRENT_LOC, challenge) } { let numerator_value := 1 let denominator_value := 1 let valid_inputs := true let public_inputs_ptr := add(calldataload(0x24), 0x24) let endpoint_ptr := add(public_inputs_ptr, mul(mload(NUM_INPUTS_LOC), 0x20)) let root_2 := mulmod(beta, 0x0c, p_clone) let input := calldataload(public_inputs_ptr) valid_inputs := and(valid_inputs, lt(input, p_clone)) let temp := addmod(input, gamma, p_clone) numerator_value := mulmod(numerator_value, add(root_1, temp), p_clone) denominator_value := mulmod(denominator_value, add(root_2, temp), p_clone) root_1 := mulmod(root_1, work_root, p_clone) root_2 := mulmod(root_2, work_root, p_clone) if iszero(valid_inputs) { mstore(0x00, PUBLIC_INPUT_GE_P_SELECTOR) revert(0x00, 0x04) } mstore(DELTA_NUMERATOR_LOC, numerator_value) mstore(DELTA_DENOMINATOR_LOC, denominator_value) } { let delta_base := mulmod(mload(C_GAMMA_LOC), addmod(mload(C_BETA_LOC), 1, p), p) let delta_numerator := delta_base { let exponent := mload(N_LOC) let count := 1 delta_numerator := mulmod(delta_numerator, delta_numerator, p) } } mstore(PLOOKUP_DELTA_NUMERATOR_LOC, delta_numerator) let delta_denominator := mulmod(delta_base, delta_base, p) delta_denominator := mulmod(delta_denominator, delta_denominator, p) mstore(PLOOKUP_DELTA_DENOMINATOR_LOC, delta_denominator) }
877,347
[ 1, 8097, 279, 587, 80, 2033, 3008, 265, 79, 14601, 225, 389, 24207, 300, 1021, 5343, 14601, 225, 389, 482, 10059, 300, 1922, 526, 434, 326, 1071, 4540, 327, 1053, 309, 14601, 353, 923, 16, 15226, 87, 3541, 19, 24089, 4629, 3932, 4571, 22753, 4883, 19, 24089, 2438, 7509, 24870, 4629, 3932, 12421, 18990, 3964, 19, 1954, 4259, 854, 923, 18254, 10392, 611, 21, 3143, 1021, 1071, 810, 2117, 353, 4041, 622, 374, 92, 3247, 16, 732, 1508, 527, 374, 92, 3247, 358, 2488, 3451, 471, 326, 769, 434, 1071, 4540, 1610, 326, 1071, 4540, 1879, 1610, 678, 21, 16, 678, 22, 16, 678, 23, 1368, 12948, 18, 8315, 1634, 353, 374, 92, 7132, 1731, 16, 1427, 1262, 374, 6511, 20, 273, 890, 225, 374, 92, 7132, 1731, 261, 31370, 810, 769, 13, 1680, 8525, 353, 326, 1592, 12948, 397, 1071, 4540, 397, 678, 21, 16, 678, 22, 16, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 565, 445, 3929, 12, 3890, 745, 892, 389, 24207, 16, 1731, 1578, 8526, 745, 892, 389, 482, 10059, 13, 3903, 1476, 1135, 261, 6430, 13, 288, 203, 3639, 1262, 13483, 653, 12, 50, 67, 29450, 16, 531, 958, 25043, 67, 706, 28489, 67, 29450, 1769, 203, 203, 3639, 2254, 5034, 1931, 4782, 1210, 1380, 31, 203, 3639, 19931, 288, 203, 5411, 1931, 4782, 1210, 1380, 519, 312, 945, 12, 6069, 67, 15934, 55, 67, 29450, 13, 203, 3639, 289, 203, 3639, 309, 261, 4718, 4782, 1210, 1380, 480, 389, 482, 10059, 18, 2469, 13, 288, 203, 5411, 15226, 17187, 67, 15934, 67, 7240, 67, 9347, 12, 4718, 4782, 1210, 1380, 16, 389, 482, 10059, 18, 2469, 1769, 203, 3639, 289, 203, 203, 3639, 19931, 288, 203, 203, 5411, 288, 203, 7734, 2231, 501, 67, 6723, 519, 527, 12, 1991, 72, 3145, 6189, 12, 20, 92, 3028, 3631, 374, 92, 3247, 13, 203, 203, 7734, 312, 2233, 12, 59, 21, 67, 61, 67, 29450, 16, 681, 12, 1991, 72, 3145, 6189, 12, 892, 67, 6723, 3631, 1043, 3719, 203, 7734, 312, 2233, 12, 59, 21, 67, 60, 67, 29450, 16, 681, 12, 1991, 72, 3145, 6189, 12, 1289, 12, 892, 67, 6723, 16, 374, 92, 3462, 13, 3631, 1043, 3719, 203, 203, 7734, 312, 2233, 12, 59, 22, 67, 61, 67, 29450, 16, 681, 12, 1991, 72, 3145, 6189, 12, 1289, 12, 892, 67, 6723, 16, 374, 92, 7132, 13, 3631, 1043, 3719, 203, 7734, 312, 2233, 12, 59, 22, 67, 60, 67, 29450, 16, 2 ]
./full_match/80001/0x8d42bb819B9f758aEe864a88dfCe9fB18F4e1073/sources/src/contracts/ContractOpenablePack.sol
@dev Add contents to an existing packId.
function addPackContents( uint256 _packId, Token[] calldata _contents, uint256[] calldata _numOfRewardUnits, address _recipient ) external payable onlyRoleWithSwitch(minterRole) nonReentrant returns (uint256 packTotalSupply, uint256 newSupplyAdded) { require(canUpdatePack[_packId], "!Allowed"); require(_contents.length > 0 && _contents.length == _numOfRewardUnits.length, "!Len"); require(balanceOf(_recipient, _packId) != 0, "!Bal"); if (!hasRole(assetRole, address(0))) { for (uint256 i = 0; i < _contents.length; i += 1) { _checkRole(assetRole, _contents[i].assetContract); } } uint256 amountPerOpen = packInfo[_packId].amountDistributedPerOpen; newSupplyAdded = createOrAddBundle(_contents, _numOfRewardUnits, _packId, amountPerOpen, true); packTotalSupply = totalSupply[_packId] + newSupplyAdded; _mint(_recipient, _packId, newSupplyAdded, ""); emit PackUpdated(_packId, _recipient, newSupplyAdded); }
859,154
[ 1, 986, 2939, 358, 392, 2062, 2298, 548, 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, 445, 527, 4420, 6323, 12, 203, 3639, 2254, 5034, 389, 2920, 548, 16, 203, 3639, 3155, 8526, 745, 892, 389, 3980, 16, 203, 3639, 2254, 5034, 8526, 745, 892, 389, 2107, 951, 17631, 1060, 7537, 16, 203, 3639, 1758, 389, 20367, 203, 565, 262, 203, 3639, 3903, 203, 3639, 8843, 429, 203, 3639, 1338, 2996, 1190, 10200, 12, 1154, 387, 2996, 13, 203, 3639, 1661, 426, 8230, 970, 203, 3639, 1135, 261, 11890, 5034, 2298, 5269, 3088, 1283, 16, 2254, 5034, 394, 3088, 1283, 8602, 13, 203, 565, 288, 203, 3639, 2583, 12, 4169, 1891, 4420, 63, 67, 2920, 548, 6487, 17528, 5042, 8863, 203, 3639, 2583, 24899, 3980, 18, 2469, 405, 374, 597, 389, 3980, 18, 2469, 422, 389, 2107, 951, 17631, 1060, 7537, 18, 2469, 16, 17528, 2891, 8863, 203, 3639, 2583, 12, 12296, 951, 24899, 20367, 16, 389, 2920, 548, 13, 480, 374, 16, 17528, 38, 287, 8863, 203, 203, 3639, 309, 16051, 5332, 2996, 12, 9406, 2996, 16, 1758, 12, 20, 20349, 288, 203, 5411, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 389, 3980, 18, 2469, 31, 277, 1011, 404, 13, 288, 203, 7734, 389, 1893, 2996, 12, 9406, 2996, 16, 389, 3980, 63, 77, 8009, 9406, 8924, 1769, 203, 5411, 289, 203, 3639, 289, 203, 203, 3639, 2254, 5034, 3844, 2173, 3678, 273, 2298, 966, 63, 67, 2920, 548, 8009, 8949, 1669, 11050, 2173, 3678, 31, 203, 3639, 394, 3088, 1283, 8602, 273, 752, 1162, 986, 3405, 24899, 3980, 16, 389, 2107, 951, 17631, 1060, 2 ]
pragma solidity ^0.5.0; /* Future Goals: - remove admins necessity - encourage contributors to allocate - needs incentive for someone to call forfeit - read from previous versions of the script DApp: - show tokens to allocate - allocate token to person with praise - leaderboard, showing amount totalReceived and totalForfeited and amount, praises https://codepen.io/lewismcarey/pen/GJZVoG - allows you to send SNT to meritocracy - add/remove contributor - add/remove adminstrator Extension: - Command: - above command = display allocation, received, withdraw button, allocate button? (might be better in dapp) - /kudos 500 "<person>" "<praise>" */ // Abstract contract for the full ERC 20 Token standard // https://github.com/ethereum/EIPs/issues/20 interface ERC20Token { /** * @notice send `_value` token to `_to` from `msg.sender` * @param _to The address of the recipient * @param _value The amount of token to be transferred * @return Whether the transfer was successful or not */ function transfer(address _to, uint256 _value) external returns (bool success); /** * @notice `msg.sender` approves `_spender` to spend `_value` tokens * @param _spender The address of the account able to transfer the tokens * @param _value The amount of tokens to be approved for transfer * @return Whether the approval was successful or not */ function approve(address _spender, uint256 _value) external returns (bool success); /** * @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` * @param _from The address of the sender * @param _to The address of the recipient * @param _value The amount of token to be transferred * @return Whether the transfer was successful or not */ function transferFrom(address _from, address _to, uint256 _value) external returns (bool success); /** * @param _owner The address from which the balance will be retrieved * @return The balance */ function balanceOf(address _owner) external view returns (uint256 balance); /** * @param _owner The address of the account owning tokens * @param _spender The address of the account able to transfer the tokens * @return Amount of remaining tokens allowed to spent */ function allowance(address _owner, address _spender) external view returns (uint256 remaining); /** * @notice return total supply of tokens */ function totalSupply() external view returns (uint256 supply); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } contract Meritocracy { struct Status { address author; string praise; uint256 amount; uint256 time; // block.timestamp } struct Contributor { address addr; uint256 allocation; // Amount they can send to other contributors, and amount they forfeit, when forfeit just zero this out and leave Token in contract, Owner can use escape to receive it back uint256 totalForfeited; // Allocations they've burnt, can be used to show non-active players. uint256 totalReceived; uint256 received; // Ignore amounts in Status struct, and use this as source of truth, can withdraw at any time // bool inPot; // Require Contributor WARN: commented because there's some edge cases not dealt with Status[] status; } ERC20Token public token; // token contract address payable public owner; // contract owner uint256 public lastForfeit; // timestamp to block admins calling forfeitAllocations too quickly address[] public registry; // array of contributor addresses uint256 public maxContributors; // Dynamic finite limit on registry. mapping(address => bool) public admins; mapping(address => Contributor) public contributors; bytes public contributorListIPFSHash; Meritocracy public previousMeritocracy; // Reference and read from previous contract // Events ----------------------------------------------------------------------------------------------- event ContributorAdded(address _contributor); event ContributorRemoved(address _contributor); event ContributorWithdrew(address _contributor); event ContributorTransaction(address _cSender, address _cReceiver); event AdminAdded(address _admin); event AdminRemoved(address _admin); event AllocationsForfeited(); event OwnerChanged(address _owner); event TokenChanged(address _token); event MaxContributorsChanged(uint256 _maxContributors); event EscapeHatchTriggered(address _executor); // Modifiers -------------------------------------------------------------------------------------------- // Functions only Owner can call modifier onlyOwner { require(msg.sender == owner); _; } // Functions only Admin can call modifier onlyAdmin { require(admins[msg.sender]); _; } // Open Functions -------------------------------------------------------------------------------------- // Split amount over each contributor in registry, any contributor can allocate? TODO maybe relax this restriction, so anyone can allocate tokens function allocate(uint256 _amount) external { // Locals // Contributor memory cAllocator = contributors[msg.sender]; // Requirements // require(cAllocator.addr != address(0)); // is sender a Contributor? TODO maybe relax this restriction. uint256 individualAmount = _amount / registry.length; // removing decimals individualAmount = (individualAmount / 1 ether * 1 ether); uint amount = individualAmount * registry.length; require(token.transferFrom(msg.sender, address(this), amount)); // Body // cAllocator.inPot = true; for (uint256 i = 0; i < registry.length; i++) { contributors[registry[i]].allocation += individualAmount; } } function getRegistry() public view returns (address[] memory) { return registry; } // Contributor Functions -------------------------------------------------------------------------------- // Allows a contributor to withdraw their received Token, when their allocation is 0 function withdraw() external { // Locals Contributor storage cReceiver = contributors[msg.sender]; // Requirements require(cReceiver.addr == msg.sender); //is sender a Contributor? require(cReceiver.received > 0); // Contributor has received some tokens require(cReceiver.allocation == 0); // Contributor must allocate all Token (or have Token burnt) before they can withdraw. // require(cReceiver.inPot); // Contributor has put some tokens into the pot // Body uint256 r = cReceiver.received; cReceiver.received = 0; // cReceiver.inPot = false; token.transfer(cReceiver.addr, r); emit ContributorWithdrew(cReceiver.addr); } // Allow Contributors to award allocated tokens to other Contributors function award(address _contributor, uint256 _amount, string memory _praise) public { // Locals Contributor storage cSender = contributors[msg.sender]; Contributor storage cReceiver = contributors[_contributor]; // Requirements require(_amount > 0); // Allow Non-Zero amounts only require(cSender.addr == msg.sender); // Ensure Contributors both exist, and isn't the same address require(cReceiver.addr == _contributor); require(cSender.addr != cReceiver.addr); // cannot send to self require(cSender.allocation >= _amount); // Ensure Sender has enough tokens to allocate // Body cSender.allocation -= _amount; // burn is not adjusted, which is done only in forfeitAllocations cReceiver.received += _amount; cReceiver.totalReceived += _amount; Status memory s = Status({ author: cSender.addr, praise: _praise, amount: _amount, time: block.timestamp }); cReceiver.status.push(s); // Record the history emit ContributorTransaction(cSender.addr, cReceiver.addr); } function getStatusLength(address _contributor) public view returns (uint) { return contributors[_contributor].status.length; } function getStatus(address _contributor, uint _index) public view returns ( address author, string memory praise, uint256 amount, uint256 time ) { author = contributors[_contributor].status[_index].author; praise = contributors[_contributor].status[_index].praise; amount = contributors[_contributor].status[_index].amount; time = contributors[_contributor].status[_index].time; } // Allow Contributor to award multiple Contributors function awardContributors(address[] calldata _contributors, uint256 _amountEach, string calldata _praise) external { // Locals Contributor storage cSender = contributors[msg.sender]; uint256 contributorsLength = _contributors.length; uint256 totalAmount = contributorsLength * _amountEach; // Requirements require(cSender.allocation >= totalAmount); // Body for (uint256 i = 0; i < contributorsLength; i++) { award(_contributors[i], _amountEach, _praise); } } // Admin Functions ------------------------------------------------------------------------------------- // Add Contributor to Registry function addContributor(address _contributor, bytes memory _contributorListIPFSHash) public onlyAdmin { addContributorWithoutHash(_contributor); // Set new IPFS hash for the list contributorListIPFSHash = _contributorListIPFSHash; } function addContributorWithoutHash(address _contributor) internal onlyAdmin { // Requirements require(registry.length + 1 <= maxContributors); // Don't go out of bounds require(contributors[_contributor].addr == address(0)); // Contributor doesn't exist // Body Contributor storage c = contributors[_contributor]; c.addr = _contributor; registry.push(_contributor); emit ContributorAdded(_contributor); } // Add Multiple Contributors to the Registry in one tx function addContributors(address[] calldata _newContributors, bytes calldata _contributorListIPFSHash) external onlyAdmin { // Locals uint256 newContributorLength = _newContributors.length; // Requirements require(registry.length + newContributorLength <= maxContributors); // Don't go out of bounds // Body for (uint256 i = 0; i < newContributorLength; i++) { addContributorWithoutHash(_newContributors[i]); } // Set new IPFS hash for the list contributorListIPFSHash = _contributorListIPFSHash; } // Remove Contributor from Registry // Note: Should not be easy to remove multiple contributors in one tx // WARN: Changed to idx, client can do loop by enumerating registry function removeContributor(uint256 idx, bytes calldata _contributorListIPFSHash) external onlyAdmin { // address _contributor // Locals uint256 registryLength = registry.length - 1; // Requirements require(idx <= registryLength); // idx needs to be smaller than registry.length - 1 OR maxContributors // Body address c = registry[idx]; // Swap & Pop! registry[idx] = registry[registryLength]; registry.pop(); delete contributors[c]; // TODO check if this works // Set new IPFS hash for the list contributorListIPFSHash = _contributorListIPFSHash; emit ContributorRemoved(c); } // Implictly sets a finite limit to registry length function setMaxContributors(uint256 _maxContributors) external onlyAdmin { require(_maxContributors > registry.length); // have to removeContributor first // Body maxContributors = _maxContributors; emit MaxContributorsChanged(maxContributors); } // Zero-out allocations for contributors, minimum once a week, if allocation still exists, add to burn function forfeitAllocations() public onlyAdmin { // Locals uint256 registryLength = registry.length; // Requirements require(block.timestamp >= lastForfeit + 6 days); // prevents admins accidently calling too quickly. // Body lastForfeit = block.timestamp; for (uint256 i = 0; i < registryLength; i++) { // should never be longer than maxContributors, see addContributor Contributor storage c = contributors[registry[i]]; c.totalForfeited += c.allocation; // Shaaaaame! c.allocation = 0; // cReceiver.inPot = false; // Contributor has to put tokens into next round } emit AllocationsForfeited(); } // Owner Functions ------------------------------------------------------------------------------------- // Set Admin flag for address to true function addAdmin(address _admin) public onlyOwner { admins[_admin] = true; emit AdminAdded(_admin); } // Set Admin flag for address to false function removeAdmin(address _admin) public onlyOwner { delete admins[_admin]; emit AdminRemoved(_admin); } // Change owner address, ideally to a management contract or multisig function changeOwner(address payable _owner) external onlyOwner { // Body removeAdmin(owner); addAdmin(_owner); owner = _owner; emit OwnerChanged(owner); } // Change Token address // WARN: call escape first, or escape(token); function changeToken(address _token) external onlyOwner { // Body // Zero-out allocation and received, send out received tokens before token switch. for (uint256 i = 0; i < registry.length; i++) { Contributor storage c = contributors[registry[i]]; uint256 r = c.received; c.received = 0; c.allocation = 0; // WARN: Should totalReceived and totalForfeited be zeroed-out? token.transfer(c.addr, r); // Transfer any owed tokens to contributor } lastForfeit = block.timestamp; token = ERC20Token(_token); emit TokenChanged(_token); } // Failsafe, Owner can escape hatch all Tokens and ETH from Contract. function escape() public onlyOwner { // Body token.transfer(owner, token.balanceOf(address(this))); owner.transfer(address(this).balance); emit EscapeHatchTriggered(msg.sender); } // Overloaded failsafe function, recourse incase changeToken is called before escape and funds are in a different token // Don't want to require in changeToken incase bad behaviour of ERC20 token function escape(address _token) external onlyOwner { // Body ERC20Token t = ERC20Token(_token); t.transfer(owner, t.balanceOf(address(this))); escape(); } // Housekeeping ----------------------------------------------------------------------------------------- // function importPreviousMeritocracyData() private onlyOwner { // onlyOwner not explicitly needed but safer than sorry, it's problem with overloaded function // // if previousMeritocracy != address(0) { // TODO better truthiness test, casting? // // // Do Stuff // // } // } // Constructor ------------------------------------------------------------------------------------------ // constructor(address _token, uint256 _maxContributors, address _previousMeritocracy) public { // } // Set Owner, Token address, initial maxContributors constructor(address _token, uint256 _maxContributors, bytes memory _contributorListIPFSHash) public { // Body owner = msg.sender; addAdmin(owner); lastForfeit = block.timestamp; token = ERC20Token(_token); maxContributors= _maxContributors; contributorListIPFSHash = _contributorListIPFSHash; // previousMeritocracy = Meritocracy(_previousMeritocracy); // importPreviousMeritocracyData() TODO } }
Set Owner, Token address, initial maxContributors Body previousMeritocracy = Meritocracy(_previousMeritocracy); importPreviousMeritocracyData() TODO
constructor(address _token, uint256 _maxContributors, bytes memory _contributorListIPFSHash) public { owner = msg.sender; addAdmin(owner); lastForfeit = block.timestamp; token = ERC20Token(_token); maxContributors= _maxContributors; contributorListIPFSHash = _contributorListIPFSHash; }
12,859,510
[ 1, 694, 16837, 16, 3155, 1758, 16, 225, 2172, 943, 442, 665, 13595, 5652, 2416, 8478, 305, 504, 354, 2431, 273, 14940, 305, 504, 354, 2431, 24899, 11515, 8478, 305, 504, 354, 2431, 1769, 1930, 8351, 8478, 305, 504, 354, 2431, 751, 1435, 2660, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 3885, 12, 2867, 389, 2316, 16, 2254, 5034, 389, 1896, 442, 665, 13595, 16, 1731, 3778, 389, 591, 19293, 682, 2579, 4931, 2310, 13, 1071, 288, 203, 3639, 3410, 273, 1234, 18, 15330, 31, 203, 3639, 527, 4446, 12, 8443, 1769, 203, 3639, 1142, 1290, 3030, 305, 273, 1203, 18, 5508, 31, 203, 3639, 1147, 273, 4232, 39, 3462, 1345, 24899, 2316, 1769, 203, 3639, 943, 442, 665, 13595, 33, 389, 1896, 442, 665, 13595, 31, 203, 3639, 31123, 682, 2579, 4931, 2310, 273, 389, 591, 19293, 682, 2579, 4931, 2310, 31, 203, 203, 203, 203, 203, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/4/0xf3a48a8324E269325D85a55199cC4eA37518EcE8/sources/SmolMuseum.sol
* @dev Contract for handling the NFT staking and set creation./
contract SmolMuseum is Ownable { using SafeMath for uint256; struct CardSet { uint256[] cardIds; uint256 tingPerDayPerCard; bool isRemoved; } SmolStudio public smolStudio; SmolTing public ting; TingBooster public tingBooster; SmolTingPot public smolTingPot; address public treasuryAddr; uint256[] public cardSetList; event Stake(address indexed user, uint256[] cardIds); event Unstake(address indexed user, uint256[] cardIds); event Harvest(address indexed user, uint256 amount); uint256 public highestCardId; mapping (uint256 => CardSet) public cardSets; mapping (uint256 => uint256) public cardToSetMap; mapping (address => mapping(uint256 => bool)) public userCards; mapping (address => mapping(uint256 => uint256)) public userPoolBoosts; mapping (address => uint256) public userLastUpdate; constructor(SmolTingPot _smolTingPotAddr, SmolStudio _smolStudioAddr, SmolTing _tingAddr, TingBooster _tingBoosterAddr, address _treasuryAddr) public { smolTingPot = _smolTingPotAddr; smolStudio = _smolStudioAddr; ting = _tingAddr; tingBooster = _tingBoosterAddr; treasuryAddr = _treasuryAddr; } function _isInArray(uint256 _value, uint256[] memory _array) internal pure returns(bool) { uint256 length = _array.length; for (uint256 i = 0; i < length; ++i) { if (_array[i] == _value) { return true; } } return false; } function _isInArray(uint256 _value, uint256[] memory _array) internal pure returns(bool) { uint256 length = _array.length; for (uint256 i = 0; i < length; ++i) { if (_array[i] == _value) { return true; } } return false; } function _isInArray(uint256 _value, uint256[] memory _array) internal pure returns(bool) { uint256 length = _array.length; for (uint256 i = 0; i < length; ++i) { if (_array[i] == _value) { return true; } } return false; } function getCardsStakedOfAddress(address _user) public view returns(bool[] memory) { bool[] memory cardsStaked = new bool[](highestCardId + 1); for (uint256 i = 0; i < highestCardId + 1; ++i) { cardsStaked[i] = userCards[_user][i]; } return cardsStaked; } function getCardsStakedOfAddress(address _user) public view returns(bool[] memory) { bool[] memory cardsStaked = new bool[](highestCardId + 1); for (uint256 i = 0; i < highestCardId + 1; ++i) { cardsStaked[i] = userCards[_user][i]; } return cardsStaked; } function getCardIdListOfSet(uint256 _setId) external view returns(uint256[] memory) { return cardSets[_setId].cardIds; } function getFullSetsOfAddress(address _user) public view returns(bool[] memory) { uint256 length = cardSetList.length; bool[] memory isFullSet = new bool[](length); for (uint256 i = 0; i < length; ++i) { uint256 setId = cardSetList[i]; if (cardSets[setId].isRemoved) { isFullSet[i] = false; continue; } bool _fullSet = true; uint256[] memory _cardIds = cardSets[setId].cardIds; for (uint256 j = 0; j < _cardIds.length; ++j) { if (userCards[_user][_cardIds[j]] == false) { _fullSet = false; break; } } isFullSet[i] = _fullSet; } return isFullSet; } function getFullSetsOfAddress(address _user) public view returns(bool[] memory) { uint256 length = cardSetList.length; bool[] memory isFullSet = new bool[](length); for (uint256 i = 0; i < length; ++i) { uint256 setId = cardSetList[i]; if (cardSets[setId].isRemoved) { isFullSet[i] = false; continue; } bool _fullSet = true; uint256[] memory _cardIds = cardSets[setId].cardIds; for (uint256 j = 0; j < _cardIds.length; ++j) { if (userCards[_user][_cardIds[j]] == false) { _fullSet = false; break; } } isFullSet[i] = _fullSet; } return isFullSet; } function getFullSetsOfAddress(address _user) public view returns(bool[] memory) { uint256 length = cardSetList.length; bool[] memory isFullSet = new bool[](length); for (uint256 i = 0; i < length; ++i) { uint256 setId = cardSetList[i]; if (cardSets[setId].isRemoved) { isFullSet[i] = false; continue; } bool _fullSet = true; uint256[] memory _cardIds = cardSets[setId].cardIds; for (uint256 j = 0; j < _cardIds.length; ++j) { if (userCards[_user][_cardIds[j]] == false) { _fullSet = false; break; } } isFullSet[i] = _fullSet; } return isFullSet; } function getFullSetsOfAddress(address _user) public view returns(bool[] memory) { uint256 length = cardSetList.length; bool[] memory isFullSet = new bool[](length); for (uint256 i = 0; i < length; ++i) { uint256 setId = cardSetList[i]; if (cardSets[setId].isRemoved) { isFullSet[i] = false; continue; } bool _fullSet = true; uint256[] memory _cardIds = cardSets[setId].cardIds; for (uint256 j = 0; j < _cardIds.length; ++j) { if (userCards[_user][_cardIds[j]] == false) { _fullSet = false; break; } } isFullSet[i] = _fullSet; } return isFullSet; } function getFullSetsOfAddress(address _user) public view returns(bool[] memory) { uint256 length = cardSetList.length; bool[] memory isFullSet = new bool[](length); for (uint256 i = 0; i < length; ++i) { uint256 setId = cardSetList[i]; if (cardSets[setId].isRemoved) { isFullSet[i] = false; continue; } bool _fullSet = true; uint256[] memory _cardIds = cardSets[setId].cardIds; for (uint256 j = 0; j < _cardIds.length; ++j) { if (userCards[_user][_cardIds[j]] == false) { _fullSet = false; break; } } isFullSet[i] = _fullSet; } return isFullSet; } function getNumOfNftsStakedForSet(address _user, uint256 _setId) public view returns(uint256) { uint256 nbStaked = 0; if (cardSets[_setId].isRemoved) return 0; uint256 length = cardSets[_setId].cardIds.length; for (uint256 j = 0; j < length; ++j) { uint256 cardId = cardSets[_setId].cardIds[j]; if (userCards[_user][cardId] == true) { nbStaked = nbStaked.add(1); } } return nbStaked; } function getNumOfNftsStakedForSet(address _user, uint256 _setId) public view returns(uint256) { uint256 nbStaked = 0; if (cardSets[_setId].isRemoved) return 0; uint256 length = cardSets[_setId].cardIds.length; for (uint256 j = 0; j < length; ++j) { uint256 cardId = cardSets[_setId].cardIds[j]; if (userCards[_user][cardId] == true) { nbStaked = nbStaked.add(1); } } return nbStaked; } function getNumOfNftsStakedForSet(address _user, uint256 _setId) public view returns(uint256) { uint256 nbStaked = 0; if (cardSets[_setId].isRemoved) return 0; uint256 length = cardSets[_setId].cardIds.length; for (uint256 j = 0; j < length; ++j) { uint256 cardId = cardSets[_setId].cardIds[j]; if (userCards[_user][cardId] == true) { nbStaked = nbStaked.add(1); } } return nbStaked; } function getNumOfNftsStakedByAddress(address _user) public view returns(uint256) { uint256 nbStaked = 0; for (uint256 i = 0; i < cardSetList.length; ++i) { nbStaked = nbStaked.add(getNumOfNftsStakedForSet(_user, cardSetList[i])); } return nbStaked; } function getNumOfNftsStakedByAddress(address _user) public view returns(uint256) { uint256 nbStaked = 0; for (uint256 i = 0; i < cardSetList.length; ++i) { nbStaked = nbStaked.add(getNumOfNftsStakedForSet(_user, cardSetList[i])); } return nbStaked; } function totalPendingTingOfAddress(address _user, bool _includeTingBooster) public view returns (uint256) { uint256 totalTingPerDay = 0; uint256 length = cardSetList.length; for (uint256 i = 0; i < length; ++i) { uint256 setId = cardSetList[i]; CardSet storage set = cardSets[setId]; if (set.isRemoved) continue; uint256 cardLength = set.cardIds.length; bool isFullSet = true; uint256 setTingPerDay = 0; for (uint256 j = 0; j < cardLength; ++j) { if (userCards[_user][set.cardIds[j]] == false) { isFullSet = false; continue; } setTingPerDay = setTingPerDay.add(set.tingPerDayPerCard); } if (isFullSet) { setTingPerDay = setTingPerDay.mul(set.bonusTingMultiplier).div(1e5); } totalTingPerDay = totalTingPerDay.add(setTingPerDay); } if (_includeTingBooster) { uint256 boostMult = tingBooster.getMultiplierOfAddress(_user).add(1e5); totalTingPerDay = totalTingPerDay.mul(boostMult).div(1e5); } uint256 lastUpdate = userLastUpdate[_user]; uint256 blockTime = block.timestamp; return blockTime.sub(lastUpdate).mul(totalTingPerDay.div(86400)); } function totalPendingTingOfAddress(address _user, bool _includeTingBooster) public view returns (uint256) { uint256 totalTingPerDay = 0; uint256 length = cardSetList.length; for (uint256 i = 0; i < length; ++i) { uint256 setId = cardSetList[i]; CardSet storage set = cardSets[setId]; if (set.isRemoved) continue; uint256 cardLength = set.cardIds.length; bool isFullSet = true; uint256 setTingPerDay = 0; for (uint256 j = 0; j < cardLength; ++j) { if (userCards[_user][set.cardIds[j]] == false) { isFullSet = false; continue; } setTingPerDay = setTingPerDay.add(set.tingPerDayPerCard); } if (isFullSet) { setTingPerDay = setTingPerDay.mul(set.bonusTingMultiplier).div(1e5); } totalTingPerDay = totalTingPerDay.add(setTingPerDay); } if (_includeTingBooster) { uint256 boostMult = tingBooster.getMultiplierOfAddress(_user).add(1e5); totalTingPerDay = totalTingPerDay.mul(boostMult).div(1e5); } uint256 lastUpdate = userLastUpdate[_user]; uint256 blockTime = block.timestamp; return blockTime.sub(lastUpdate).mul(totalTingPerDay.div(86400)); } function totalPendingTingOfAddress(address _user, bool _includeTingBooster) public view returns (uint256) { uint256 totalTingPerDay = 0; uint256 length = cardSetList.length; for (uint256 i = 0; i < length; ++i) { uint256 setId = cardSetList[i]; CardSet storage set = cardSets[setId]; if (set.isRemoved) continue; uint256 cardLength = set.cardIds.length; bool isFullSet = true; uint256 setTingPerDay = 0; for (uint256 j = 0; j < cardLength; ++j) { if (userCards[_user][set.cardIds[j]] == false) { isFullSet = false; continue; } setTingPerDay = setTingPerDay.add(set.tingPerDayPerCard); } if (isFullSet) { setTingPerDay = setTingPerDay.mul(set.bonusTingMultiplier).div(1e5); } totalTingPerDay = totalTingPerDay.add(setTingPerDay); } if (_includeTingBooster) { uint256 boostMult = tingBooster.getMultiplierOfAddress(_user).add(1e5); totalTingPerDay = totalTingPerDay.mul(boostMult).div(1e5); } uint256 lastUpdate = userLastUpdate[_user]; uint256 blockTime = block.timestamp; return blockTime.sub(lastUpdate).mul(totalTingPerDay.div(86400)); } function totalPendingTingOfAddress(address _user, bool _includeTingBooster) public view returns (uint256) { uint256 totalTingPerDay = 0; uint256 length = cardSetList.length; for (uint256 i = 0; i < length; ++i) { uint256 setId = cardSetList[i]; CardSet storage set = cardSets[setId]; if (set.isRemoved) continue; uint256 cardLength = set.cardIds.length; bool isFullSet = true; uint256 setTingPerDay = 0; for (uint256 j = 0; j < cardLength; ++j) { if (userCards[_user][set.cardIds[j]] == false) { isFullSet = false; continue; } setTingPerDay = setTingPerDay.add(set.tingPerDayPerCard); } if (isFullSet) { setTingPerDay = setTingPerDay.mul(set.bonusTingMultiplier).div(1e5); } totalTingPerDay = totalTingPerDay.add(setTingPerDay); } if (_includeTingBooster) { uint256 boostMult = tingBooster.getMultiplierOfAddress(_user).add(1e5); totalTingPerDay = totalTingPerDay.mul(boostMult).div(1e5); } uint256 lastUpdate = userLastUpdate[_user]; uint256 blockTime = block.timestamp; return blockTime.sub(lastUpdate).mul(totalTingPerDay.div(86400)); } function totalPendingTingOfAddress(address _user, bool _includeTingBooster) public view returns (uint256) { uint256 totalTingPerDay = 0; uint256 length = cardSetList.length; for (uint256 i = 0; i < length; ++i) { uint256 setId = cardSetList[i]; CardSet storage set = cardSets[setId]; if (set.isRemoved) continue; uint256 cardLength = set.cardIds.length; bool isFullSet = true; uint256 setTingPerDay = 0; for (uint256 j = 0; j < cardLength; ++j) { if (userCards[_user][set.cardIds[j]] == false) { isFullSet = false; continue; } setTingPerDay = setTingPerDay.add(set.tingPerDayPerCard); } if (isFullSet) { setTingPerDay = setTingPerDay.mul(set.bonusTingMultiplier).div(1e5); } totalTingPerDay = totalTingPerDay.add(setTingPerDay); } if (_includeTingBooster) { uint256 boostMult = tingBooster.getMultiplierOfAddress(_user).add(1e5); totalTingPerDay = totalTingPerDay.mul(boostMult).div(1e5); } uint256 lastUpdate = userLastUpdate[_user]; uint256 blockTime = block.timestamp; return blockTime.sub(lastUpdate).mul(totalTingPerDay.div(86400)); } function totalPendingTingOfAddress(address _user, bool _includeTingBooster) public view returns (uint256) { uint256 totalTingPerDay = 0; uint256 length = cardSetList.length; for (uint256 i = 0; i < length; ++i) { uint256 setId = cardSetList[i]; CardSet storage set = cardSets[setId]; if (set.isRemoved) continue; uint256 cardLength = set.cardIds.length; bool isFullSet = true; uint256 setTingPerDay = 0; for (uint256 j = 0; j < cardLength; ++j) { if (userCards[_user][set.cardIds[j]] == false) { isFullSet = false; continue; } setTingPerDay = setTingPerDay.add(set.tingPerDayPerCard); } if (isFullSet) { setTingPerDay = setTingPerDay.mul(set.bonusTingMultiplier).div(1e5); } totalTingPerDay = totalTingPerDay.add(setTingPerDay); } if (_includeTingBooster) { uint256 boostMult = tingBooster.getMultiplierOfAddress(_user).add(1e5); totalTingPerDay = totalTingPerDay.mul(boostMult).div(1e5); } uint256 lastUpdate = userLastUpdate[_user]; uint256 blockTime = block.timestamp; return blockTime.sub(lastUpdate).mul(totalTingPerDay.div(86400)); } function totalPendingTingOfAddressFromBooster(address _user) external view returns (uint256) { uint256 totalPending = totalPendingTingOfAddress(_user, false); uint256 userBoost = tingBooster.getMultiplierOfAddress(_user).add(1e5); return totalPending.mul(userBoost).div(1e5); } function getBoosterForUser(address _addr, uint256 _pid) public view returns (uint256) { return userPoolBoosts[_addr][_pid]; } function setHighestCardId(uint256 _highestId) public onlyOwner { require(_highestId > 0, "Set if minimum 1 card is staked."); highestCardId = _highestId; } function addCardSet(uint256 _setId, uint256[] memory _cardIds, uint256 _bonusTingMultiplier, uint256 _tingPerDayPerCard, uint256[] memory _poolBoosts, bool _isBooster) public onlyOwner { removeCardSet(_setId); uint256 length = _cardIds.length; for (uint256 i = 0; i < length; ++i) { uint256 cardId = _cardIds[i]; if (cardId > highestCardId) { highestCardId = cardId; } } if (_isInArray(_setId, cardSetList) == false) { cardSetList.push(_setId); } cardSets[_setId] = CardSet({ cardIds: _cardIds, bonusTingMultiplier: _bonusTingMultiplier, tingPerDayPerCard: _tingPerDayPerCard, isBooster: _isBooster, poolBoosts: _poolBoosts, isRemoved: false }); } function addCardSet(uint256 _setId, uint256[] memory _cardIds, uint256 _bonusTingMultiplier, uint256 _tingPerDayPerCard, uint256[] memory _poolBoosts, bool _isBooster) public onlyOwner { removeCardSet(_setId); uint256 length = _cardIds.length; for (uint256 i = 0; i < length; ++i) { uint256 cardId = _cardIds[i]; if (cardId > highestCardId) { highestCardId = cardId; } } if (_isInArray(_setId, cardSetList) == false) { cardSetList.push(_setId); } cardSets[_setId] = CardSet({ cardIds: _cardIds, bonusTingMultiplier: _bonusTingMultiplier, tingPerDayPerCard: _tingPerDayPerCard, isBooster: _isBooster, poolBoosts: _poolBoosts, isRemoved: false }); } function addCardSet(uint256 _setId, uint256[] memory _cardIds, uint256 _bonusTingMultiplier, uint256 _tingPerDayPerCard, uint256[] memory _poolBoosts, bool _isBooster) public onlyOwner { removeCardSet(_setId); uint256 length = _cardIds.length; for (uint256 i = 0; i < length; ++i) { uint256 cardId = _cardIds[i]; if (cardId > highestCardId) { highestCardId = cardId; } } if (_isInArray(_setId, cardSetList) == false) { cardSetList.push(_setId); } cardSets[_setId] = CardSet({ cardIds: _cardIds, bonusTingMultiplier: _bonusTingMultiplier, tingPerDayPerCard: _tingPerDayPerCard, isBooster: _isBooster, poolBoosts: _poolBoosts, isRemoved: false }); } require(cardToSetMap[cardId] == 0, "Card already assigned to a set"); cardToSetMap[cardId] = _setId; function addCardSet(uint256 _setId, uint256[] memory _cardIds, uint256 _bonusTingMultiplier, uint256 _tingPerDayPerCard, uint256[] memory _poolBoosts, bool _isBooster) public onlyOwner { removeCardSet(_setId); uint256 length = _cardIds.length; for (uint256 i = 0; i < length; ++i) { uint256 cardId = _cardIds[i]; if (cardId > highestCardId) { highestCardId = cardId; } } if (_isInArray(_setId, cardSetList) == false) { cardSetList.push(_setId); } cardSets[_setId] = CardSet({ cardIds: _cardIds, bonusTingMultiplier: _bonusTingMultiplier, tingPerDayPerCard: _tingPerDayPerCard, isBooster: _isBooster, poolBoosts: _poolBoosts, isRemoved: false }); } function addCardSet(uint256 _setId, uint256[] memory _cardIds, uint256 _bonusTingMultiplier, uint256 _tingPerDayPerCard, uint256[] memory _poolBoosts, bool _isBooster) public onlyOwner { removeCardSet(_setId); uint256 length = _cardIds.length; for (uint256 i = 0; i < length; ++i) { uint256 cardId = _cardIds[i]; if (cardId > highestCardId) { highestCardId = cardId; } } if (_isInArray(_setId, cardSetList) == false) { cardSetList.push(_setId); } cardSets[_setId] = CardSet({ cardIds: _cardIds, bonusTingMultiplier: _bonusTingMultiplier, tingPerDayPerCard: _tingPerDayPerCard, isBooster: _isBooster, poolBoosts: _poolBoosts, isRemoved: false }); } function setTingRateOfSets(uint256[] memory _setIds, uint256[] memory _tingPerDayPerCard) public onlyOwner { require(_setIds.length == _tingPerDayPerCard.length, "_setId and _tingPerDayPerCard have different length"); for (uint256 i = 0; i < _setIds.length; ++i) { require(cardSets[_setIds[i]].cardIds.length > 0, "Set is empty"); cardSets[_setIds[i]].tingPerDayPerCard = _tingPerDayPerCard[i]; } } function setTingRateOfSets(uint256[] memory _setIds, uint256[] memory _tingPerDayPerCard) public onlyOwner { require(_setIds.length == _tingPerDayPerCard.length, "_setId and _tingPerDayPerCard have different length"); for (uint256 i = 0; i < _setIds.length; ++i) { require(cardSets[_setIds[i]].cardIds.length > 0, "Set is empty"); cardSets[_setIds[i]].tingPerDayPerCard = _tingPerDayPerCard[i]; } } function setBonusTingMultiplierOfSets(uint256[] memory _setIds, uint256[] memory _bonusTingMultiplier) public onlyOwner { require(_setIds.length == _bonusTingMultiplier.length, "_setId and _tingPerDayPerCard have different length"); for (uint256 i = 0; i < _setIds.length; ++i) { require(cardSets[_setIds[i]].cardIds.length > 0, "Set is empty"); cardSets[_setIds[i]].bonusTingMultiplier = _bonusTingMultiplier[i]; } } function setBonusTingMultiplierOfSets(uint256[] memory _setIds, uint256[] memory _bonusTingMultiplier) public onlyOwner { require(_setIds.length == _bonusTingMultiplier.length, "_setId and _tingPerDayPerCard have different length"); for (uint256 i = 0; i < _setIds.length; ++i) { require(cardSets[_setIds[i]].cardIds.length > 0, "Set is empty"); cardSets[_setIds[i]].bonusTingMultiplier = _bonusTingMultiplier[i]; } } function removeCardSet(uint256 _setId) public onlyOwner { uint256 length = cardSets[_setId].cardIds.length; for (uint256 i = 0; i < length; ++i) { uint256 cardId = cardSets[_setId].cardIds[i]; cardToSetMap[cardId] = 0; } delete cardSets[_setId].cardIds; cardSets[_setId].isRemoved = true; cardSets[_setId].isBooster = false; } function removeCardSet(uint256 _setId) public onlyOwner { uint256 length = cardSets[_setId].cardIds.length; for (uint256 i = 0; i < length; ++i) { uint256 cardId = cardSets[_setId].cardIds[i]; cardToSetMap[cardId] = 0; } delete cardSets[_setId].cardIds; cardSets[_setId].isRemoved = true; cardSets[_setId].isBooster = false; } function harvest() public { uint256 pendingTing = totalPendingTingOfAddress(msg.sender, true); userLastUpdate[msg.sender] = block.timestamp; if (pendingTing > 0) { ting.mint(msg.sender, pendingTing); ting.addClaimed(pendingTing); } emit Harvest(msg.sender, pendingTing); } function harvest() public { uint256 pendingTing = totalPendingTingOfAddress(msg.sender, true); userLastUpdate[msg.sender] = block.timestamp; if (pendingTing > 0) { ting.mint(msg.sender, pendingTing); ting.addClaimed(pendingTing); } emit Harvest(msg.sender, pendingTing); } function stake(uint256[] memory _cardIds) public { require(_cardIds.length > 0, "you need to stake something"); uint256 length = _cardIds.length; bool onlyBoosters = true; bool onlyNoBoosters = true; for (uint256 i = 0; i < length; ++i) { uint256 cardId = _cardIds[i]; require(userCards[msg.sender][cardId] == false, "item already staked"); require(cardToSetMap[cardId] != 0, "you can't stake that"); if (cardSets[cardToSetMap[cardId]].tingPerDayPerCard > 0) onlyBoosters = false; if (cardSets[cardToSetMap[cardId]].isBooster == true) onlyNoBoosters = false; } if (onlyNoBoosters == false) { for (uint256 i = 0; i < length; ++i) { uint256 cardId = _cardIds[i]; if (cardSets[cardToSetMap[cardId]].isBooster) { uint256 boostLength = cardSets[cardToSetMap[cardId]].poolBoosts.length; uint256[] memory currentBoosts = new uint256[](boostLength); for (uint256 j = 0; j < boostLength; ++j) { currentBoosts[j] = userPoolBoosts[msg.sender][j]; uint256 newBoost = cardSets[cardToSetMap[cardId]].poolBoosts[j]; if (cardSets[cardToSetMap[cardId]].poolBoosts[j] > 0) { address staker = msg.sender; smolTingPot.withdraw(j, 0, staker); userPoolBoosts[msg.sender][j] = currentBoosts[j].add(newBoost); } } } } } for (uint256 i = 0; i < _cardIds.length; ++i) { amounts[i] = 1; } smolStudio.safeBatchTransferFrom(msg.sender, address(this), _cardIds, amounts, ""); for (uint256 i = 0; i < length; ++i) { uint256 cardId = _cardIds[i]; userCards[msg.sender][cardId] = true; } emit Stake(msg.sender, _cardIds); } function stake(uint256[] memory _cardIds) public { require(_cardIds.length > 0, "you need to stake something"); uint256 length = _cardIds.length; bool onlyBoosters = true; bool onlyNoBoosters = true; for (uint256 i = 0; i < length; ++i) { uint256 cardId = _cardIds[i]; require(userCards[msg.sender][cardId] == false, "item already staked"); require(cardToSetMap[cardId] != 0, "you can't stake that"); if (cardSets[cardToSetMap[cardId]].tingPerDayPerCard > 0) onlyBoosters = false; if (cardSets[cardToSetMap[cardId]].isBooster == true) onlyNoBoosters = false; } if (onlyNoBoosters == false) { for (uint256 i = 0; i < length; ++i) { uint256 cardId = _cardIds[i]; if (cardSets[cardToSetMap[cardId]].isBooster) { uint256 boostLength = cardSets[cardToSetMap[cardId]].poolBoosts.length; uint256[] memory currentBoosts = new uint256[](boostLength); for (uint256 j = 0; j < boostLength; ++j) { currentBoosts[j] = userPoolBoosts[msg.sender][j]; uint256 newBoost = cardSets[cardToSetMap[cardId]].poolBoosts[j]; if (cardSets[cardToSetMap[cardId]].poolBoosts[j] > 0) { address staker = msg.sender; smolTingPot.withdraw(j, 0, staker); userPoolBoosts[msg.sender][j] = currentBoosts[j].add(newBoost); } } } } } for (uint256 i = 0; i < _cardIds.length; ++i) { amounts[i] = 1; } smolStudio.safeBatchTransferFrom(msg.sender, address(this), _cardIds, amounts, ""); for (uint256 i = 0; i < length; ++i) { uint256 cardId = _cardIds[i]; userCards[msg.sender][cardId] = true; } emit Stake(msg.sender, _cardIds); } if (onlyBoosters == false) harvest(); function stake(uint256[] memory _cardIds) public { require(_cardIds.length > 0, "you need to stake something"); uint256 length = _cardIds.length; bool onlyBoosters = true; bool onlyNoBoosters = true; for (uint256 i = 0; i < length; ++i) { uint256 cardId = _cardIds[i]; require(userCards[msg.sender][cardId] == false, "item already staked"); require(cardToSetMap[cardId] != 0, "you can't stake that"); if (cardSets[cardToSetMap[cardId]].tingPerDayPerCard > 0) onlyBoosters = false; if (cardSets[cardToSetMap[cardId]].isBooster == true) onlyNoBoosters = false; } if (onlyNoBoosters == false) { for (uint256 i = 0; i < length; ++i) { uint256 cardId = _cardIds[i]; if (cardSets[cardToSetMap[cardId]].isBooster) { uint256 boostLength = cardSets[cardToSetMap[cardId]].poolBoosts.length; uint256[] memory currentBoosts = new uint256[](boostLength); for (uint256 j = 0; j < boostLength; ++j) { currentBoosts[j] = userPoolBoosts[msg.sender][j]; uint256 newBoost = cardSets[cardToSetMap[cardId]].poolBoosts[j]; if (cardSets[cardToSetMap[cardId]].poolBoosts[j] > 0) { address staker = msg.sender; smolTingPot.withdraw(j, 0, staker); userPoolBoosts[msg.sender][j] = currentBoosts[j].add(newBoost); } } } } } for (uint256 i = 0; i < _cardIds.length; ++i) { amounts[i] = 1; } smolStudio.safeBatchTransferFrom(msg.sender, address(this), _cardIds, amounts, ""); for (uint256 i = 0; i < length; ++i) { uint256 cardId = _cardIds[i]; userCards[msg.sender][cardId] = true; } emit Stake(msg.sender, _cardIds); } function stake(uint256[] memory _cardIds) public { require(_cardIds.length > 0, "you need to stake something"); uint256 length = _cardIds.length; bool onlyBoosters = true; bool onlyNoBoosters = true; for (uint256 i = 0; i < length; ++i) { uint256 cardId = _cardIds[i]; require(userCards[msg.sender][cardId] == false, "item already staked"); require(cardToSetMap[cardId] != 0, "you can't stake that"); if (cardSets[cardToSetMap[cardId]].tingPerDayPerCard > 0) onlyBoosters = false; if (cardSets[cardToSetMap[cardId]].isBooster == true) onlyNoBoosters = false; } if (onlyNoBoosters == false) { for (uint256 i = 0; i < length; ++i) { uint256 cardId = _cardIds[i]; if (cardSets[cardToSetMap[cardId]].isBooster) { uint256 boostLength = cardSets[cardToSetMap[cardId]].poolBoosts.length; uint256[] memory currentBoosts = new uint256[](boostLength); for (uint256 j = 0; j < boostLength; ++j) { currentBoosts[j] = userPoolBoosts[msg.sender][j]; uint256 newBoost = cardSets[cardToSetMap[cardId]].poolBoosts[j]; if (cardSets[cardToSetMap[cardId]].poolBoosts[j] > 0) { address staker = msg.sender; smolTingPot.withdraw(j, 0, staker); userPoolBoosts[msg.sender][j] = currentBoosts[j].add(newBoost); } } } } } for (uint256 i = 0; i < _cardIds.length; ++i) { amounts[i] = 1; } smolStudio.safeBatchTransferFrom(msg.sender, address(this), _cardIds, amounts, ""); for (uint256 i = 0; i < length; ++i) { uint256 cardId = _cardIds[i]; userCards[msg.sender][cardId] = true; } emit Stake(msg.sender, _cardIds); } function stake(uint256[] memory _cardIds) public { require(_cardIds.length > 0, "you need to stake something"); uint256 length = _cardIds.length; bool onlyBoosters = true; bool onlyNoBoosters = true; for (uint256 i = 0; i < length; ++i) { uint256 cardId = _cardIds[i]; require(userCards[msg.sender][cardId] == false, "item already staked"); require(cardToSetMap[cardId] != 0, "you can't stake that"); if (cardSets[cardToSetMap[cardId]].tingPerDayPerCard > 0) onlyBoosters = false; if (cardSets[cardToSetMap[cardId]].isBooster == true) onlyNoBoosters = false; } if (onlyNoBoosters == false) { for (uint256 i = 0; i < length; ++i) { uint256 cardId = _cardIds[i]; if (cardSets[cardToSetMap[cardId]].isBooster) { uint256 boostLength = cardSets[cardToSetMap[cardId]].poolBoosts.length; uint256[] memory currentBoosts = new uint256[](boostLength); for (uint256 j = 0; j < boostLength; ++j) { currentBoosts[j] = userPoolBoosts[msg.sender][j]; uint256 newBoost = cardSets[cardToSetMap[cardId]].poolBoosts[j]; if (cardSets[cardToSetMap[cardId]].poolBoosts[j] > 0) { address staker = msg.sender; smolTingPot.withdraw(j, 0, staker); userPoolBoosts[msg.sender][j] = currentBoosts[j].add(newBoost); } } } } } for (uint256 i = 0; i < _cardIds.length; ++i) { amounts[i] = 1; } smolStudio.safeBatchTransferFrom(msg.sender, address(this), _cardIds, amounts, ""); for (uint256 i = 0; i < length; ++i) { uint256 cardId = _cardIds[i]; userCards[msg.sender][cardId] = true; } emit Stake(msg.sender, _cardIds); } function stake(uint256[] memory _cardIds) public { require(_cardIds.length > 0, "you need to stake something"); uint256 length = _cardIds.length; bool onlyBoosters = true; bool onlyNoBoosters = true; for (uint256 i = 0; i < length; ++i) { uint256 cardId = _cardIds[i]; require(userCards[msg.sender][cardId] == false, "item already staked"); require(cardToSetMap[cardId] != 0, "you can't stake that"); if (cardSets[cardToSetMap[cardId]].tingPerDayPerCard > 0) onlyBoosters = false; if (cardSets[cardToSetMap[cardId]].isBooster == true) onlyNoBoosters = false; } if (onlyNoBoosters == false) { for (uint256 i = 0; i < length; ++i) { uint256 cardId = _cardIds[i]; if (cardSets[cardToSetMap[cardId]].isBooster) { uint256 boostLength = cardSets[cardToSetMap[cardId]].poolBoosts.length; uint256[] memory currentBoosts = new uint256[](boostLength); for (uint256 j = 0; j < boostLength; ++j) { currentBoosts[j] = userPoolBoosts[msg.sender][j]; uint256 newBoost = cardSets[cardToSetMap[cardId]].poolBoosts[j]; if (cardSets[cardToSetMap[cardId]].poolBoosts[j] > 0) { address staker = msg.sender; smolTingPot.withdraw(j, 0, staker); userPoolBoosts[msg.sender][j] = currentBoosts[j].add(newBoost); } } } } } for (uint256 i = 0; i < _cardIds.length; ++i) { amounts[i] = 1; } smolStudio.safeBatchTransferFrom(msg.sender, address(this), _cardIds, amounts, ""); for (uint256 i = 0; i < length; ++i) { uint256 cardId = _cardIds[i]; userCards[msg.sender][cardId] = true; } emit Stake(msg.sender, _cardIds); } function stake(uint256[] memory _cardIds) public { require(_cardIds.length > 0, "you need to stake something"); uint256 length = _cardIds.length; bool onlyBoosters = true; bool onlyNoBoosters = true; for (uint256 i = 0; i < length; ++i) { uint256 cardId = _cardIds[i]; require(userCards[msg.sender][cardId] == false, "item already staked"); require(cardToSetMap[cardId] != 0, "you can't stake that"); if (cardSets[cardToSetMap[cardId]].tingPerDayPerCard > 0) onlyBoosters = false; if (cardSets[cardToSetMap[cardId]].isBooster == true) onlyNoBoosters = false; } if (onlyNoBoosters == false) { for (uint256 i = 0; i < length; ++i) { uint256 cardId = _cardIds[i]; if (cardSets[cardToSetMap[cardId]].isBooster) { uint256 boostLength = cardSets[cardToSetMap[cardId]].poolBoosts.length; uint256[] memory currentBoosts = new uint256[](boostLength); for (uint256 j = 0; j < boostLength; ++j) { currentBoosts[j] = userPoolBoosts[msg.sender][j]; uint256 newBoost = cardSets[cardToSetMap[cardId]].poolBoosts[j]; if (cardSets[cardToSetMap[cardId]].poolBoosts[j] > 0) { address staker = msg.sender; smolTingPot.withdraw(j, 0, staker); userPoolBoosts[msg.sender][j] = currentBoosts[j].add(newBoost); } } } } } for (uint256 i = 0; i < _cardIds.length; ++i) { amounts[i] = 1; } smolStudio.safeBatchTransferFrom(msg.sender, address(this), _cardIds, amounts, ""); for (uint256 i = 0; i < length; ++i) { uint256 cardId = _cardIds[i]; userCards[msg.sender][cardId] = true; } emit Stake(msg.sender, _cardIds); } uint256[] memory amounts = new uint256[](_cardIds.length); function stake(uint256[] memory _cardIds) public { require(_cardIds.length > 0, "you need to stake something"); uint256 length = _cardIds.length; bool onlyBoosters = true; bool onlyNoBoosters = true; for (uint256 i = 0; i < length; ++i) { uint256 cardId = _cardIds[i]; require(userCards[msg.sender][cardId] == false, "item already staked"); require(cardToSetMap[cardId] != 0, "you can't stake that"); if (cardSets[cardToSetMap[cardId]].tingPerDayPerCard > 0) onlyBoosters = false; if (cardSets[cardToSetMap[cardId]].isBooster == true) onlyNoBoosters = false; } if (onlyNoBoosters == false) { for (uint256 i = 0; i < length; ++i) { uint256 cardId = _cardIds[i]; if (cardSets[cardToSetMap[cardId]].isBooster) { uint256 boostLength = cardSets[cardToSetMap[cardId]].poolBoosts.length; uint256[] memory currentBoosts = new uint256[](boostLength); for (uint256 j = 0; j < boostLength; ++j) { currentBoosts[j] = userPoolBoosts[msg.sender][j]; uint256 newBoost = cardSets[cardToSetMap[cardId]].poolBoosts[j]; if (cardSets[cardToSetMap[cardId]].poolBoosts[j] > 0) { address staker = msg.sender; smolTingPot.withdraw(j, 0, staker); userPoolBoosts[msg.sender][j] = currentBoosts[j].add(newBoost); } } } } } for (uint256 i = 0; i < _cardIds.length; ++i) { amounts[i] = 1; } smolStudio.safeBatchTransferFrom(msg.sender, address(this), _cardIds, amounts, ""); for (uint256 i = 0; i < length; ++i) { uint256 cardId = _cardIds[i]; userCards[msg.sender][cardId] = true; } emit Stake(msg.sender, _cardIds); } function stake(uint256[] memory _cardIds) public { require(_cardIds.length > 0, "you need to stake something"); uint256 length = _cardIds.length; bool onlyBoosters = true; bool onlyNoBoosters = true; for (uint256 i = 0; i < length; ++i) { uint256 cardId = _cardIds[i]; require(userCards[msg.sender][cardId] == false, "item already staked"); require(cardToSetMap[cardId] != 0, "you can't stake that"); if (cardSets[cardToSetMap[cardId]].tingPerDayPerCard > 0) onlyBoosters = false; if (cardSets[cardToSetMap[cardId]].isBooster == true) onlyNoBoosters = false; } if (onlyNoBoosters == false) { for (uint256 i = 0; i < length; ++i) { uint256 cardId = _cardIds[i]; if (cardSets[cardToSetMap[cardId]].isBooster) { uint256 boostLength = cardSets[cardToSetMap[cardId]].poolBoosts.length; uint256[] memory currentBoosts = new uint256[](boostLength); for (uint256 j = 0; j < boostLength; ++j) { currentBoosts[j] = userPoolBoosts[msg.sender][j]; uint256 newBoost = cardSets[cardToSetMap[cardId]].poolBoosts[j]; if (cardSets[cardToSetMap[cardId]].poolBoosts[j] > 0) { address staker = msg.sender; smolTingPot.withdraw(j, 0, staker); userPoolBoosts[msg.sender][j] = currentBoosts[j].add(newBoost); } } } } } for (uint256 i = 0; i < _cardIds.length; ++i) { amounts[i] = 1; } smolStudio.safeBatchTransferFrom(msg.sender, address(this), _cardIds, amounts, ""); for (uint256 i = 0; i < length; ++i) { uint256 cardId = _cardIds[i]; userCards[msg.sender][cardId] = true; } emit Stake(msg.sender, _cardIds); } function unstake(uint256[] memory _cardIds) public { require(_cardIds.length > 0, "input at least 1 card id"); uint256 length = _cardIds.length; bool onlyBoosters = true; bool onlyNoBoosters = true; for (uint256 i = 0; i < length; ++i) { uint256 cardId = _cardIds[i]; require(userCards[msg.sender][cardId] == true, "Card not staked"); if (cardSets[cardToSetMap[cardId]].tingPerDayPerCard > 0) onlyBoosters = false; if (cardSets[cardToSetMap[cardId]].isBooster == true) onlyNoBoosters = false; } if (onlyBoosters == false) harvest(); if (onlyNoBoosters == false) { for (uint256 i = 0; i < length; ++i) { uint256 cardId = _cardIds[i]; if (cardSets[cardToSetMap[cardId]].isBooster) { uint256 boostLength = cardSets[cardToSetMap[cardId]].poolBoosts.length; uint256[] memory currentBoosts = new uint256[](boostLength); for (uint256 j = 0; j < boostLength; ++j) { currentBoosts[j] = userPoolBoosts[msg.sender][j]; uint256 newBoost = cardSets[cardToSetMap[cardId]].poolBoosts[j]; if (cardSets[cardToSetMap[cardId]].poolBoosts[j] > 0) { address staker = msg.sender; smolTingPot.withdraw(j, 0, staker); userPoolBoosts[msg.sender][j] = currentBoosts[j].sub(newBoost); } } } } } for (uint256 i = 0; i < _cardIds.length; ++i) { amounts[i] = 1; } smolStudio.safeBatchTransferFrom(address(this), msg.sender, _cardIds, amounts, ""); emit Unstake(msg.sender, _cardIds); } function unstake(uint256[] memory _cardIds) public { require(_cardIds.length > 0, "input at least 1 card id"); uint256 length = _cardIds.length; bool onlyBoosters = true; bool onlyNoBoosters = true; for (uint256 i = 0; i < length; ++i) { uint256 cardId = _cardIds[i]; require(userCards[msg.sender][cardId] == true, "Card not staked"); if (cardSets[cardToSetMap[cardId]].tingPerDayPerCard > 0) onlyBoosters = false; if (cardSets[cardToSetMap[cardId]].isBooster == true) onlyNoBoosters = false; } if (onlyBoosters == false) harvest(); if (onlyNoBoosters == false) { for (uint256 i = 0; i < length; ++i) { uint256 cardId = _cardIds[i]; if (cardSets[cardToSetMap[cardId]].isBooster) { uint256 boostLength = cardSets[cardToSetMap[cardId]].poolBoosts.length; uint256[] memory currentBoosts = new uint256[](boostLength); for (uint256 j = 0; j < boostLength; ++j) { currentBoosts[j] = userPoolBoosts[msg.sender][j]; uint256 newBoost = cardSets[cardToSetMap[cardId]].poolBoosts[j]; if (cardSets[cardToSetMap[cardId]].poolBoosts[j] > 0) { address staker = msg.sender; smolTingPot.withdraw(j, 0, staker); userPoolBoosts[msg.sender][j] = currentBoosts[j].sub(newBoost); } } } } } for (uint256 i = 0; i < _cardIds.length; ++i) { amounts[i] = 1; } smolStudio.safeBatchTransferFrom(address(this), msg.sender, _cardIds, amounts, ""); emit Unstake(msg.sender, _cardIds); } function unstake(uint256[] memory _cardIds) public { require(_cardIds.length > 0, "input at least 1 card id"); uint256 length = _cardIds.length; bool onlyBoosters = true; bool onlyNoBoosters = true; for (uint256 i = 0; i < length; ++i) { uint256 cardId = _cardIds[i]; require(userCards[msg.sender][cardId] == true, "Card not staked"); if (cardSets[cardToSetMap[cardId]].tingPerDayPerCard > 0) onlyBoosters = false; if (cardSets[cardToSetMap[cardId]].isBooster == true) onlyNoBoosters = false; } if (onlyBoosters == false) harvest(); if (onlyNoBoosters == false) { for (uint256 i = 0; i < length; ++i) { uint256 cardId = _cardIds[i]; if (cardSets[cardToSetMap[cardId]].isBooster) { uint256 boostLength = cardSets[cardToSetMap[cardId]].poolBoosts.length; uint256[] memory currentBoosts = new uint256[](boostLength); for (uint256 j = 0; j < boostLength; ++j) { currentBoosts[j] = userPoolBoosts[msg.sender][j]; uint256 newBoost = cardSets[cardToSetMap[cardId]].poolBoosts[j]; if (cardSets[cardToSetMap[cardId]].poolBoosts[j] > 0) { address staker = msg.sender; smolTingPot.withdraw(j, 0, staker); userPoolBoosts[msg.sender][j] = currentBoosts[j].sub(newBoost); } } } } } for (uint256 i = 0; i < _cardIds.length; ++i) { amounts[i] = 1; } smolStudio.safeBatchTransferFrom(address(this), msg.sender, _cardIds, amounts, ""); emit Unstake(msg.sender, _cardIds); } function unstake(uint256[] memory _cardIds) public { require(_cardIds.length > 0, "input at least 1 card id"); uint256 length = _cardIds.length; bool onlyBoosters = true; bool onlyNoBoosters = true; for (uint256 i = 0; i < length; ++i) { uint256 cardId = _cardIds[i]; require(userCards[msg.sender][cardId] == true, "Card not staked"); if (cardSets[cardToSetMap[cardId]].tingPerDayPerCard > 0) onlyBoosters = false; if (cardSets[cardToSetMap[cardId]].isBooster == true) onlyNoBoosters = false; } if (onlyBoosters == false) harvest(); if (onlyNoBoosters == false) { for (uint256 i = 0; i < length; ++i) { uint256 cardId = _cardIds[i]; if (cardSets[cardToSetMap[cardId]].isBooster) { uint256 boostLength = cardSets[cardToSetMap[cardId]].poolBoosts.length; uint256[] memory currentBoosts = new uint256[](boostLength); for (uint256 j = 0; j < boostLength; ++j) { currentBoosts[j] = userPoolBoosts[msg.sender][j]; uint256 newBoost = cardSets[cardToSetMap[cardId]].poolBoosts[j]; if (cardSets[cardToSetMap[cardId]].poolBoosts[j] > 0) { address staker = msg.sender; smolTingPot.withdraw(j, 0, staker); userPoolBoosts[msg.sender][j] = currentBoosts[j].sub(newBoost); } } } } } for (uint256 i = 0; i < _cardIds.length; ++i) { amounts[i] = 1; } smolStudio.safeBatchTransferFrom(address(this), msg.sender, _cardIds, amounts, ""); emit Unstake(msg.sender, _cardIds); } function unstake(uint256[] memory _cardIds) public { require(_cardIds.length > 0, "input at least 1 card id"); uint256 length = _cardIds.length; bool onlyBoosters = true; bool onlyNoBoosters = true; for (uint256 i = 0; i < length; ++i) { uint256 cardId = _cardIds[i]; require(userCards[msg.sender][cardId] == true, "Card not staked"); if (cardSets[cardToSetMap[cardId]].tingPerDayPerCard > 0) onlyBoosters = false; if (cardSets[cardToSetMap[cardId]].isBooster == true) onlyNoBoosters = false; } if (onlyBoosters == false) harvest(); if (onlyNoBoosters == false) { for (uint256 i = 0; i < length; ++i) { uint256 cardId = _cardIds[i]; if (cardSets[cardToSetMap[cardId]].isBooster) { uint256 boostLength = cardSets[cardToSetMap[cardId]].poolBoosts.length; uint256[] memory currentBoosts = new uint256[](boostLength); for (uint256 j = 0; j < boostLength; ++j) { currentBoosts[j] = userPoolBoosts[msg.sender][j]; uint256 newBoost = cardSets[cardToSetMap[cardId]].poolBoosts[j]; if (cardSets[cardToSetMap[cardId]].poolBoosts[j] > 0) { address staker = msg.sender; smolTingPot.withdraw(j, 0, staker); userPoolBoosts[msg.sender][j] = currentBoosts[j].sub(newBoost); } } } } } for (uint256 i = 0; i < _cardIds.length; ++i) { amounts[i] = 1; } smolStudio.safeBatchTransferFrom(address(this), msg.sender, _cardIds, amounts, ""); emit Unstake(msg.sender, _cardIds); } function unstake(uint256[] memory _cardIds) public { require(_cardIds.length > 0, "input at least 1 card id"); uint256 length = _cardIds.length; bool onlyBoosters = true; bool onlyNoBoosters = true; for (uint256 i = 0; i < length; ++i) { uint256 cardId = _cardIds[i]; require(userCards[msg.sender][cardId] == true, "Card not staked"); if (cardSets[cardToSetMap[cardId]].tingPerDayPerCard > 0) onlyBoosters = false; if (cardSets[cardToSetMap[cardId]].isBooster == true) onlyNoBoosters = false; } if (onlyBoosters == false) harvest(); if (onlyNoBoosters == false) { for (uint256 i = 0; i < length; ++i) { uint256 cardId = _cardIds[i]; if (cardSets[cardToSetMap[cardId]].isBooster) { uint256 boostLength = cardSets[cardToSetMap[cardId]].poolBoosts.length; uint256[] memory currentBoosts = new uint256[](boostLength); for (uint256 j = 0; j < boostLength; ++j) { currentBoosts[j] = userPoolBoosts[msg.sender][j]; uint256 newBoost = cardSets[cardToSetMap[cardId]].poolBoosts[j]; if (cardSets[cardToSetMap[cardId]].poolBoosts[j] > 0) { address staker = msg.sender; smolTingPot.withdraw(j, 0, staker); userPoolBoosts[msg.sender][j] = currentBoosts[j].sub(newBoost); } } } } } for (uint256 i = 0; i < _cardIds.length; ++i) { amounts[i] = 1; } smolStudio.safeBatchTransferFrom(address(this), msg.sender, _cardIds, amounts, ""); emit Unstake(msg.sender, _cardIds); } function unstake(uint256[] memory _cardIds) public { require(_cardIds.length > 0, "input at least 1 card id"); uint256 length = _cardIds.length; bool onlyBoosters = true; bool onlyNoBoosters = true; for (uint256 i = 0; i < length; ++i) { uint256 cardId = _cardIds[i]; require(userCards[msg.sender][cardId] == true, "Card not staked"); if (cardSets[cardToSetMap[cardId]].tingPerDayPerCard > 0) onlyBoosters = false; if (cardSets[cardToSetMap[cardId]].isBooster == true) onlyNoBoosters = false; } if (onlyBoosters == false) harvest(); if (onlyNoBoosters == false) { for (uint256 i = 0; i < length; ++i) { uint256 cardId = _cardIds[i]; if (cardSets[cardToSetMap[cardId]].isBooster) { uint256 boostLength = cardSets[cardToSetMap[cardId]].poolBoosts.length; uint256[] memory currentBoosts = new uint256[](boostLength); for (uint256 j = 0; j < boostLength; ++j) { currentBoosts[j] = userPoolBoosts[msg.sender][j]; uint256 newBoost = cardSets[cardToSetMap[cardId]].poolBoosts[j]; if (cardSets[cardToSetMap[cardId]].poolBoosts[j] > 0) { address staker = msg.sender; smolTingPot.withdraw(j, 0, staker); userPoolBoosts[msg.sender][j] = currentBoosts[j].sub(newBoost); } } } } } for (uint256 i = 0; i < _cardIds.length; ++i) { amounts[i] = 1; } smolStudio.safeBatchTransferFrom(address(this), msg.sender, _cardIds, amounts, ""); emit Unstake(msg.sender, _cardIds); } uint256[] memory amounts = new uint256[](_cardIds.length); function unstake(uint256[] memory _cardIds) public { require(_cardIds.length > 0, "input at least 1 card id"); uint256 length = _cardIds.length; bool onlyBoosters = true; bool onlyNoBoosters = true; for (uint256 i = 0; i < length; ++i) { uint256 cardId = _cardIds[i]; require(userCards[msg.sender][cardId] == true, "Card not staked"); if (cardSets[cardToSetMap[cardId]].tingPerDayPerCard > 0) onlyBoosters = false; if (cardSets[cardToSetMap[cardId]].isBooster == true) onlyNoBoosters = false; } if (onlyBoosters == false) harvest(); if (onlyNoBoosters == false) { for (uint256 i = 0; i < length; ++i) { uint256 cardId = _cardIds[i]; if (cardSets[cardToSetMap[cardId]].isBooster) { uint256 boostLength = cardSets[cardToSetMap[cardId]].poolBoosts.length; uint256[] memory currentBoosts = new uint256[](boostLength); for (uint256 j = 0; j < boostLength; ++j) { currentBoosts[j] = userPoolBoosts[msg.sender][j]; uint256 newBoost = cardSets[cardToSetMap[cardId]].poolBoosts[j]; if (cardSets[cardToSetMap[cardId]].poolBoosts[j] > 0) { address staker = msg.sender; smolTingPot.withdraw(j, 0, staker); userPoolBoosts[msg.sender][j] = currentBoosts[j].sub(newBoost); } } } } } for (uint256 i = 0; i < _cardIds.length; ++i) { amounts[i] = 1; } smolStudio.safeBatchTransferFrom(address(this), msg.sender, _cardIds, amounts, ""); emit Unstake(msg.sender, _cardIds); } function emergencyUnstake(uint256[] memory _cardIds) public { userLastUpdate[msg.sender] = block.timestamp; uint256 length = _cardIds.length; bool onlyNoBoosters = true; for (uint256 i = 0; i < length; ++i) { uint256 cardId = _cardIds[i]; require(userCards[msg.sender][cardId] == true, "Card not staked"); userCards[msg.sender][cardId] = false; if (cardSets[cardToSetMap[cardId]].isBooster == true) onlyNoBoosters = false; } if (onlyNoBoosters == false) { for (uint256 i = 0; i < length; ++i) { uint256 cardId = _cardIds[i]; if (cardSets[cardToSetMap[cardId]].isBooster) { uint256 boostLength = cardSets[cardToSetMap[cardId]].poolBoosts.length; uint256[] memory currentBoosts = new uint256[](boostLength); for (uint256 j = 0; j < boostLength; ++j) { currentBoosts[j] = userPoolBoosts[msg.sender][j]; uint256 newBoost = cardSets[cardToSetMap[cardId]].poolBoosts[j]; if (cardSets[cardToSetMap[cardId]].poolBoosts[j] > 0) { userPoolBoosts[msg.sender][j] = currentBoosts[j].sub(newBoost); } } } } } for (uint256 i = 0; i < _cardIds.length; ++i) { amounts[i] = 1; } smolStudio.safeBatchTransferFrom(address(this), msg.sender, _cardIds, amounts, ""); } function emergencyUnstake(uint256[] memory _cardIds) public { userLastUpdate[msg.sender] = block.timestamp; uint256 length = _cardIds.length; bool onlyNoBoosters = true; for (uint256 i = 0; i < length; ++i) { uint256 cardId = _cardIds[i]; require(userCards[msg.sender][cardId] == true, "Card not staked"); userCards[msg.sender][cardId] = false; if (cardSets[cardToSetMap[cardId]].isBooster == true) onlyNoBoosters = false; } if (onlyNoBoosters == false) { for (uint256 i = 0; i < length; ++i) { uint256 cardId = _cardIds[i]; if (cardSets[cardToSetMap[cardId]].isBooster) { uint256 boostLength = cardSets[cardToSetMap[cardId]].poolBoosts.length; uint256[] memory currentBoosts = new uint256[](boostLength); for (uint256 j = 0; j < boostLength; ++j) { currentBoosts[j] = userPoolBoosts[msg.sender][j]; uint256 newBoost = cardSets[cardToSetMap[cardId]].poolBoosts[j]; if (cardSets[cardToSetMap[cardId]].poolBoosts[j] > 0) { userPoolBoosts[msg.sender][j] = currentBoosts[j].sub(newBoost); } } } } } for (uint256 i = 0; i < _cardIds.length; ++i) { amounts[i] = 1; } smolStudio.safeBatchTransferFrom(address(this), msg.sender, _cardIds, amounts, ""); } function emergencyUnstake(uint256[] memory _cardIds) public { userLastUpdate[msg.sender] = block.timestamp; uint256 length = _cardIds.length; bool onlyNoBoosters = true; for (uint256 i = 0; i < length; ++i) { uint256 cardId = _cardIds[i]; require(userCards[msg.sender][cardId] == true, "Card not staked"); userCards[msg.sender][cardId] = false; if (cardSets[cardToSetMap[cardId]].isBooster == true) onlyNoBoosters = false; } if (onlyNoBoosters == false) { for (uint256 i = 0; i < length; ++i) { uint256 cardId = _cardIds[i]; if (cardSets[cardToSetMap[cardId]].isBooster) { uint256 boostLength = cardSets[cardToSetMap[cardId]].poolBoosts.length; uint256[] memory currentBoosts = new uint256[](boostLength); for (uint256 j = 0; j < boostLength; ++j) { currentBoosts[j] = userPoolBoosts[msg.sender][j]; uint256 newBoost = cardSets[cardToSetMap[cardId]].poolBoosts[j]; if (cardSets[cardToSetMap[cardId]].poolBoosts[j] > 0) { userPoolBoosts[msg.sender][j] = currentBoosts[j].sub(newBoost); } } } } } for (uint256 i = 0; i < _cardIds.length; ++i) { amounts[i] = 1; } smolStudio.safeBatchTransferFrom(address(this), msg.sender, _cardIds, amounts, ""); } function emergencyUnstake(uint256[] memory _cardIds) public { userLastUpdate[msg.sender] = block.timestamp; uint256 length = _cardIds.length; bool onlyNoBoosters = true; for (uint256 i = 0; i < length; ++i) { uint256 cardId = _cardIds[i]; require(userCards[msg.sender][cardId] == true, "Card not staked"); userCards[msg.sender][cardId] = false; if (cardSets[cardToSetMap[cardId]].isBooster == true) onlyNoBoosters = false; } if (onlyNoBoosters == false) { for (uint256 i = 0; i < length; ++i) { uint256 cardId = _cardIds[i]; if (cardSets[cardToSetMap[cardId]].isBooster) { uint256 boostLength = cardSets[cardToSetMap[cardId]].poolBoosts.length; uint256[] memory currentBoosts = new uint256[](boostLength); for (uint256 j = 0; j < boostLength; ++j) { currentBoosts[j] = userPoolBoosts[msg.sender][j]; uint256 newBoost = cardSets[cardToSetMap[cardId]].poolBoosts[j]; if (cardSets[cardToSetMap[cardId]].poolBoosts[j] > 0) { userPoolBoosts[msg.sender][j] = currentBoosts[j].sub(newBoost); } } } } } for (uint256 i = 0; i < _cardIds.length; ++i) { amounts[i] = 1; } smolStudio.safeBatchTransferFrom(address(this), msg.sender, _cardIds, amounts, ""); } function emergencyUnstake(uint256[] memory _cardIds) public { userLastUpdate[msg.sender] = block.timestamp; uint256 length = _cardIds.length; bool onlyNoBoosters = true; for (uint256 i = 0; i < length; ++i) { uint256 cardId = _cardIds[i]; require(userCards[msg.sender][cardId] == true, "Card not staked"); userCards[msg.sender][cardId] = false; if (cardSets[cardToSetMap[cardId]].isBooster == true) onlyNoBoosters = false; } if (onlyNoBoosters == false) { for (uint256 i = 0; i < length; ++i) { uint256 cardId = _cardIds[i]; if (cardSets[cardToSetMap[cardId]].isBooster) { uint256 boostLength = cardSets[cardToSetMap[cardId]].poolBoosts.length; uint256[] memory currentBoosts = new uint256[](boostLength); for (uint256 j = 0; j < boostLength; ++j) { currentBoosts[j] = userPoolBoosts[msg.sender][j]; uint256 newBoost = cardSets[cardToSetMap[cardId]].poolBoosts[j]; if (cardSets[cardToSetMap[cardId]].poolBoosts[j] > 0) { userPoolBoosts[msg.sender][j] = currentBoosts[j].sub(newBoost); } } } } } for (uint256 i = 0; i < _cardIds.length; ++i) { amounts[i] = 1; } smolStudio.safeBatchTransferFrom(address(this), msg.sender, _cardIds, amounts, ""); } function emergencyUnstake(uint256[] memory _cardIds) public { userLastUpdate[msg.sender] = block.timestamp; uint256 length = _cardIds.length; bool onlyNoBoosters = true; for (uint256 i = 0; i < length; ++i) { uint256 cardId = _cardIds[i]; require(userCards[msg.sender][cardId] == true, "Card not staked"); userCards[msg.sender][cardId] = false; if (cardSets[cardToSetMap[cardId]].isBooster == true) onlyNoBoosters = false; } if (onlyNoBoosters == false) { for (uint256 i = 0; i < length; ++i) { uint256 cardId = _cardIds[i]; if (cardSets[cardToSetMap[cardId]].isBooster) { uint256 boostLength = cardSets[cardToSetMap[cardId]].poolBoosts.length; uint256[] memory currentBoosts = new uint256[](boostLength); for (uint256 j = 0; j < boostLength; ++j) { currentBoosts[j] = userPoolBoosts[msg.sender][j]; uint256 newBoost = cardSets[cardToSetMap[cardId]].poolBoosts[j]; if (cardSets[cardToSetMap[cardId]].poolBoosts[j] > 0) { userPoolBoosts[msg.sender][j] = currentBoosts[j].sub(newBoost); } } } } } for (uint256 i = 0; i < _cardIds.length; ++i) { amounts[i] = 1; } smolStudio.safeBatchTransferFrom(address(this), msg.sender, _cardIds, amounts, ""); } function emergencyUnstake(uint256[] memory _cardIds) public { userLastUpdate[msg.sender] = block.timestamp; uint256 length = _cardIds.length; bool onlyNoBoosters = true; for (uint256 i = 0; i < length; ++i) { uint256 cardId = _cardIds[i]; require(userCards[msg.sender][cardId] == true, "Card not staked"); userCards[msg.sender][cardId] = false; if (cardSets[cardToSetMap[cardId]].isBooster == true) onlyNoBoosters = false; } if (onlyNoBoosters == false) { for (uint256 i = 0; i < length; ++i) { uint256 cardId = _cardIds[i]; if (cardSets[cardToSetMap[cardId]].isBooster) { uint256 boostLength = cardSets[cardToSetMap[cardId]].poolBoosts.length; uint256[] memory currentBoosts = new uint256[](boostLength); for (uint256 j = 0; j < boostLength; ++j) { currentBoosts[j] = userPoolBoosts[msg.sender][j]; uint256 newBoost = cardSets[cardToSetMap[cardId]].poolBoosts[j]; if (cardSets[cardToSetMap[cardId]].poolBoosts[j] > 0) { userPoolBoosts[msg.sender][j] = currentBoosts[j].sub(newBoost); } } } } } for (uint256 i = 0; i < _cardIds.length; ++i) { amounts[i] = 1; } smolStudio.safeBatchTransferFrom(address(this), msg.sender, _cardIds, amounts, ""); } uint256[] memory amounts = new uint256[](_cardIds.length); function emergencyUnstake(uint256[] memory _cardIds) public { userLastUpdate[msg.sender] = block.timestamp; uint256 length = _cardIds.length; bool onlyNoBoosters = true; for (uint256 i = 0; i < length; ++i) { uint256 cardId = _cardIds[i]; require(userCards[msg.sender][cardId] == true, "Card not staked"); userCards[msg.sender][cardId] = false; if (cardSets[cardToSetMap[cardId]].isBooster == true) onlyNoBoosters = false; } if (onlyNoBoosters == false) { for (uint256 i = 0; i < length; ++i) { uint256 cardId = _cardIds[i]; if (cardSets[cardToSetMap[cardId]].isBooster) { uint256 boostLength = cardSets[cardToSetMap[cardId]].poolBoosts.length; uint256[] memory currentBoosts = new uint256[](boostLength); for (uint256 j = 0; j < boostLength; ++j) { currentBoosts[j] = userPoolBoosts[msg.sender][j]; uint256 newBoost = cardSets[cardToSetMap[cardId]].poolBoosts[j]; if (cardSets[cardToSetMap[cardId]].poolBoosts[j] > 0) { userPoolBoosts[msg.sender][j] = currentBoosts[j].sub(newBoost); } } } } } for (uint256 i = 0; i < _cardIds.length; ++i) { amounts[i] = 1; } smolStudio.safeBatchTransferFrom(address(this), msg.sender, _cardIds, amounts, ""); } function updateTingBoosterAddress(TingBooster _tingBoosterAddress) public onlyOwner{ tingBooster = _tingBoosterAddress; } function updateSmolTingPotAddress(SmolTingPot _smolTingPotAddress) public onlyOwner{ smolTingPot = _smolTingPotAddress; } function treasury(address _treasuryAddr) public { require(msg.sender == treasuryAddr, "Only current treasury address can update."); treasuryAddr = _treasuryAddr; } function onERC1155Received(address _operator, address _from, uint256 _id, uint256 _amount, bytes calldata _data) external returns(bytes4) { return 0xf23a6e61; } function onERC1155BatchReceived(address _operator, address _from, uint256[] calldata _ids, uint256[] calldata _amounts, bytes calldata _data) external returns(bytes4) { return 0xbc197c81; } function supportsInterface(bytes4 interfaceID) external view returns (bool) { } }
16,980,938
[ 1, 8924, 364, 5057, 326, 423, 4464, 384, 6159, 471, 444, 6710, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 9425, 355, 49, 1202, 379, 353, 14223, 6914, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 565, 1958, 14338, 694, 288, 203, 3639, 2254, 5034, 8526, 5270, 2673, 31, 203, 3639, 2254, 5034, 268, 310, 2173, 4245, 2173, 6415, 31, 203, 3639, 1426, 353, 10026, 31, 203, 565, 289, 203, 203, 565, 9425, 355, 510, 4484, 1071, 3029, 355, 510, 4484, 31, 203, 565, 9425, 355, 56, 310, 1071, 268, 310, 31, 203, 565, 399, 310, 26653, 264, 1071, 268, 310, 26653, 264, 31, 203, 565, 9425, 355, 56, 310, 18411, 1071, 3029, 355, 56, 310, 18411, 31, 203, 565, 1758, 1071, 9787, 345, 22498, 3178, 31, 203, 203, 565, 2254, 5034, 8526, 1071, 5270, 694, 682, 31, 203, 203, 203, 565, 871, 934, 911, 12, 2867, 8808, 729, 16, 2254, 5034, 8526, 5270, 2673, 1769, 203, 565, 871, 1351, 334, 911, 12, 2867, 8808, 729, 16, 2254, 5034, 8526, 5270, 2673, 1769, 203, 565, 871, 670, 297, 26923, 12, 2867, 8808, 729, 16, 2254, 5034, 3844, 1769, 203, 203, 565, 2254, 5034, 1071, 9742, 6415, 548, 31, 203, 565, 2874, 261, 11890, 5034, 516, 14338, 694, 13, 1071, 5270, 2785, 31, 203, 565, 2874, 261, 11890, 5034, 516, 2254, 5034, 13, 1071, 5270, 25208, 863, 31, 203, 565, 2874, 261, 2867, 516, 2874, 12, 11890, 5034, 516, 1426, 3719, 1071, 729, 30492, 31, 203, 565, 2874, 261, 2867, 516, 2874, 12, 11890, 5034, 516, 2254, 5034, 3719, 1071, 729, 2864, 26653, 87, 31, 203, 565, 2874, 261, 2867, 2 ]
pragma solidity ^0.4.18; import './FuturesContract.sol'; import './oraclizeAPI.sol'; contract MarketPlace is usingOraclize { // Enum definitions enum UserLoginStatus { Online, Offline, Archieved } // Unscoped variables string public binanceBaseAPI = "https://api.binance.com/api/v3/ticker/price?symbol="; string[] public availablePairings = [ 'ETHEOS', 'ETHTRX', 'ETHOMG', 'ETHQTM' ]; uint256 constant timeStampInterval = 3*3600; uint256 public userOnlineCount; address owner; // Struct definitions struct User { bool exist; // For existance validation string name; UserLoginStatus status; // User online status uint256[] futuresContractID; // Stores list of signed contracts bytes32 passwordHash; } address[] userAddresses; uint256[] unsignedFuturesContactIds; // Mapping data struct mapping(address => User) users; mapping(uint256 => FuturesContract) signedFuturesContracts; mapping(uint256 => FuturesContract) unsignedFuturesContracts; // Event Logs // Admin Management Function Modifiers modifier onlyOwner() { require(msg.sender == owner);_; } // User Management Function Modifiers modifier userExist() { require(users[msg.sender].exist);_; } modifier notUserExist() { require(!users[msg.sender].exist);_; } modifier userIsOnline() { require(users[msg.sender].status == UserLoginStatus.Online);_; } // Contructor function MarketPlace() public { owner = msg.sender; } function signContractOf(address _seller, address _contractAddress) public payable userExist userIsOnline { // Sign contract from another User require(users[_seller].exist); User seller = users[_seller]; FuturesContract sellerContract = FuturesContract.at(_contractAddress); sellerContract.signContract(msg.sender); } function createContract(uint256 _expiryDate, uint256 _bettingPairs, uint256 _bettingPrice, string _position) public payable userExist userIsOnline { // User create new unsigned contract User currentUser = users[msg.sender]; string memory bettingAPI = strConcat(binanceBaseAPI, _bettingPairs); FuturesContract newContract = (new FuturesContract).value(msg.sender)( msg.sender, _expiryDate, _bettingPairs, _bettingPrice, _position, bettingAPI ); currentUser.futuresContractID.push(newContract.address); } // Admin Update Functions function updatePairings(string _newPairing) public onlyOwner { // Update Existing Pairing with ticker availablePairings.push(_newPairing); } // User Account Management Function function registerUser(string _name, string _password) public notUserExist { // Params Validation require(bytes(_name).length > 3); require(bytes(_password).length > 3); // Register new user to Contract users[msg.sender] = User({ exist: true, name: _name, status: UserLoginStatus.Offline, futuresContractID: new uint256[](0), passwordHash: keccak256(_password, _name) }); } function loginUser(string _name, string _password) public userExist { // Authenticate and set user login status to online require(authenticate(msg.sender, _name, _password)); users[msg.sender].status = UserLoginStatus.Online; userOnlineCount++; } function logoutUser() public userExist { // Authenticate and set user login status to offline User storage currentUser = users[msg.sender]; require(currentUser.status == UserLoginStatus.Online); currentUser.status = UserLoginStatus.Offline; userOnlineCount--; } function authenticate(address _user, string _name, string _password) private view returns(bool) { // Authenticate Caller User by verifying password return(users[_user].passwordHash == keccak256(_password, _name)); } }
User online status
UserLoginStatus status;
12,661,588
[ 1, 1299, 12365, 1267, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2177, 5358, 1482, 1267, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/3/0xD5eCd70DD7F6aA73d8295EB878AA5B2BD2c76512/sources/HotPotToken.sol
* @dev mint amount to address/
function mint(address account, uint256 amount) public onlyCreator { _mint(account, amount); }
5,076,406
[ 1, 81, 474, 3844, 358, 1758, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 312, 474, 12, 2867, 2236, 16, 2254, 5034, 3844, 13, 1071, 1338, 10636, 288, 203, 540, 389, 81, 474, 12, 4631, 16, 3844, 1769, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// Sources flattened with hardhat v2.6.0 https://hardhat.org // File @openzeppelin/contracts/math/SafeMath.sol@v3.4.1-solc-0.7-2 // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } pragma solidity >=0.6.0 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } pragma solidity >= 0.6.0 < 0.8.0; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, 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 { using EnumerableSet for EnumerableSet.AddressSet; using Address for address; struct RoleData { EnumerableSet.AddressSet members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view returns (bool) { return _roles[role].members.contains(account); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view returns (address) { return _roles[role].members.at(index); } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant"); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke"); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, _roles[role].adminRole, adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } } pragma solidity ^0.6.12; contract PaymentContract is AccessControl { using SafeMath for uint256; string public name = "Cardino Payment Contract"; address public owner; uint256 public decimals = 10 ** 18; // list of addresses for owners and marketing wallet address[] private owners = [0xB3BEB19190DbfDaf17782A656210A9D5DbC84BB3, 0x5c1C906e89b59569e020a84b7958014f210cA255, 0xe10E9a58B3139Fe0EE67EbF18C27D0C41aE0668C]; address private marketing = 0x40Fe68980068909E98d204A152759251961CC788; uint256 private totalPercent = 100; // mapping will allow us to create a relationship of investor to their current remaining balance mapping( address => uint256 ) public _currentBalance; uint256 public marketingWalletPortion = 40; uint256 public shareholdersPercentage = totalPercent.sub(marketingWalletPortion); uint256 public individualShareholderPercent = shareholdersPercentage.div(3); event MarketingWalletPercentageChanged( uint256 newPercentage); event EtherReceived(address from, uint256 amount); bytes32 public constant OWNERS = keccak256("OWNERS"); bytes32 public constant MARKETING = keccak256("MARKETING"); constructor () public { owner = msg.sender; _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setupRole(OWNERS, owners[0]); _setupRole(OWNERS, owners[1]); _setupRole(OWNERS, owners[2]); _setupRole(MARKETING, marketing); } receive() external payable { uint256 ethSent = msg.value; uint256 marketingShare = (ethSent * marketingWalletPortion) / 100; uint256 leftOver = ethSent - marketingShare; uint256 shareholdersShare = leftOver / 3; for(uint256 i=0; i < owners.length; i++){ _currentBalance[owners[i]] = _currentBalance[owners[i]] + shareholdersShare; } _currentBalance[marketing] = _currentBalance[marketing] + (marketingShare); emit EtherReceived(msg.sender, msg.value); } function updateMarketingPercentage(uint256 newMarketingCut) public { if( hasRole(OWNERS, msg.sender) == true) { if(newMarketingCut <= 40){ marketingWalletPortion = newMarketingCut; shareholdersPercentage = totalPercent.sub(marketingWalletPortion); individualShareholderPercent = shareholdersPercentage.div(3); emit MarketingWalletPercentageChanged(newMarketingCut); } } } function withdrawBalanceOwner() public { if(_currentBalance[msg.sender] > 0){ uint256 amountToPay = _currentBalance[msg.sender]; address payable withdrawee; if(hasRole(OWNERS, msg.sender)){ _currentBalance[msg.sender] = _currentBalance[msg.sender].sub(amountToPay); withdrawee = payable(msg.sender); withdrawee.transfer(amountToPay); } } } function checkBalance() external view returns (uint256 balance){ return _currentBalance[msg.sender]; } function checkTotalBalance() external view returns (uint256 totalBalance) { if(hasRole(OWNERS, msg.sender) || hasRole(MARKETING, msg.sender)){ return address(this).balance; } } function withdrawMarketing() public { if(hasRole(MARKETING, msg.sender)){ uint256 amountToPay = _currentBalance[msg.sender]; if(amountToPay > 0){ _currentBalance[msg.sender] = _currentBalance[msg.sender].sub(amountToPay); address payable marketingPayable = payable(marketing); marketingPayable.transfer(amountToPay); } } } function updateMarketingWalletAddress(address newAddress) public { if(hasRole(DEFAULT_ADMIN_ROLE, msg.sender)){ address oldAddress = marketing; if(newAddress != oldAddress){ revokeRole(MARKETING, marketing); grantRole(MARKETING, newAddress); marketing = newAddress; _currentBalance[newAddress] = _currentBalance[oldAddress]; _currentBalance[oldAddress] = 0; } } } }
list of addresses for owners and marketing wallet mapping will allow us to create a relationship of investor to their current remaining balance
contract PaymentContract is AccessControl { using SafeMath for uint256; string public name = "Cardino Payment Contract"; address public owner; uint256 public decimals = 10 ** 18; address[] private owners = [0xB3BEB19190DbfDaf17782A656210A9D5DbC84BB3, 0x5c1C906e89b59569e020a84b7958014f210cA255, 0xe10E9a58B3139Fe0EE67EbF18C27D0C41aE0668C]; address private marketing = 0x40Fe68980068909E98d204A152759251961CC788; uint256 private totalPercent = 100; mapping( address => uint256 ) public _currentBalance; uint256 public marketingWalletPortion = 40; uint256 public shareholdersPercentage = totalPercent.sub(marketingWalletPortion); uint256 public individualShareholderPercent = shareholdersPercentage.div(3); event MarketingWalletPercentageChanged( uint256 newPercentage); event EtherReceived(address from, uint256 amount); bytes32 public constant OWNERS = keccak256("OWNERS"); bytes32 public constant MARKETING = keccak256("MARKETING"); constructor () public { owner = msg.sender; _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setupRole(OWNERS, owners[0]); _setupRole(OWNERS, owners[1]); _setupRole(OWNERS, owners[2]); _setupRole(MARKETING, marketing); } receive() external payable { uint256 ethSent = msg.value; uint256 marketingShare = (ethSent * marketingWalletPortion) / 100; uint256 leftOver = ethSent - marketingShare; uint256 shareholdersShare = leftOver / 3; for(uint256 i=0; i < owners.length; i++){ _currentBalance[owners[i]] = _currentBalance[owners[i]] + shareholdersShare; } _currentBalance[marketing] = _currentBalance[marketing] + (marketingShare); emit EtherReceived(msg.sender, msg.value); } receive() external payable { uint256 ethSent = msg.value; uint256 marketingShare = (ethSent * marketingWalletPortion) / 100; uint256 leftOver = ethSent - marketingShare; uint256 shareholdersShare = leftOver / 3; for(uint256 i=0; i < owners.length; i++){ _currentBalance[owners[i]] = _currentBalance[owners[i]] + shareholdersShare; } _currentBalance[marketing] = _currentBalance[marketing] + (marketingShare); emit EtherReceived(msg.sender, msg.value); } function updateMarketingPercentage(uint256 newMarketingCut) public { if( hasRole(OWNERS, msg.sender) == true) { if(newMarketingCut <= 40){ marketingWalletPortion = newMarketingCut; shareholdersPercentage = totalPercent.sub(marketingWalletPortion); individualShareholderPercent = shareholdersPercentage.div(3); emit MarketingWalletPercentageChanged(newMarketingCut); } } } function updateMarketingPercentage(uint256 newMarketingCut) public { if( hasRole(OWNERS, msg.sender) == true) { if(newMarketingCut <= 40){ marketingWalletPortion = newMarketingCut; shareholdersPercentage = totalPercent.sub(marketingWalletPortion); individualShareholderPercent = shareholdersPercentage.div(3); emit MarketingWalletPercentageChanged(newMarketingCut); } } } function updateMarketingPercentage(uint256 newMarketingCut) public { if( hasRole(OWNERS, msg.sender) == true) { if(newMarketingCut <= 40){ marketingWalletPortion = newMarketingCut; shareholdersPercentage = totalPercent.sub(marketingWalletPortion); individualShareholderPercent = shareholdersPercentage.div(3); emit MarketingWalletPercentageChanged(newMarketingCut); } } } function withdrawBalanceOwner() public { if(_currentBalance[msg.sender] > 0){ uint256 amountToPay = _currentBalance[msg.sender]; address payable withdrawee; if(hasRole(OWNERS, msg.sender)){ _currentBalance[msg.sender] = _currentBalance[msg.sender].sub(amountToPay); withdrawee = payable(msg.sender); withdrawee.transfer(amountToPay); } } } function withdrawBalanceOwner() public { if(_currentBalance[msg.sender] > 0){ uint256 amountToPay = _currentBalance[msg.sender]; address payable withdrawee; if(hasRole(OWNERS, msg.sender)){ _currentBalance[msg.sender] = _currentBalance[msg.sender].sub(amountToPay); withdrawee = payable(msg.sender); withdrawee.transfer(amountToPay); } } } function withdrawBalanceOwner() public { if(_currentBalance[msg.sender] > 0){ uint256 amountToPay = _currentBalance[msg.sender]; address payable withdrawee; if(hasRole(OWNERS, msg.sender)){ _currentBalance[msg.sender] = _currentBalance[msg.sender].sub(amountToPay); withdrawee = payable(msg.sender); withdrawee.transfer(amountToPay); } } } function checkBalance() external view returns (uint256 balance){ return _currentBalance[msg.sender]; } function checkTotalBalance() external view returns (uint256 totalBalance) { if(hasRole(OWNERS, msg.sender) || hasRole(MARKETING, msg.sender)){ return address(this).balance; } } function checkTotalBalance() external view returns (uint256 totalBalance) { if(hasRole(OWNERS, msg.sender) || hasRole(MARKETING, msg.sender)){ return address(this).balance; } } function withdrawMarketing() public { if(hasRole(MARKETING, msg.sender)){ uint256 amountToPay = _currentBalance[msg.sender]; if(amountToPay > 0){ _currentBalance[msg.sender] = _currentBalance[msg.sender].sub(amountToPay); address payable marketingPayable = payable(marketing); marketingPayable.transfer(amountToPay); } } } function withdrawMarketing() public { if(hasRole(MARKETING, msg.sender)){ uint256 amountToPay = _currentBalance[msg.sender]; if(amountToPay > 0){ _currentBalance[msg.sender] = _currentBalance[msg.sender].sub(amountToPay); address payable marketingPayable = payable(marketing); marketingPayable.transfer(amountToPay); } } } function withdrawMarketing() public { if(hasRole(MARKETING, msg.sender)){ uint256 amountToPay = _currentBalance[msg.sender]; if(amountToPay > 0){ _currentBalance[msg.sender] = _currentBalance[msg.sender].sub(amountToPay); address payable marketingPayable = payable(marketing); marketingPayable.transfer(amountToPay); } } } function updateMarketingWalletAddress(address newAddress) public { if(hasRole(DEFAULT_ADMIN_ROLE, msg.sender)){ address oldAddress = marketing; if(newAddress != oldAddress){ revokeRole(MARKETING, marketing); grantRole(MARKETING, newAddress); marketing = newAddress; _currentBalance[newAddress] = _currentBalance[oldAddress]; _currentBalance[oldAddress] = 0; } } } function updateMarketingWalletAddress(address newAddress) public { if(hasRole(DEFAULT_ADMIN_ROLE, msg.sender)){ address oldAddress = marketing; if(newAddress != oldAddress){ revokeRole(MARKETING, marketing); grantRole(MARKETING, newAddress); marketing = newAddress; _currentBalance[newAddress] = _currentBalance[oldAddress]; _currentBalance[oldAddress] = 0; } } } function updateMarketingWalletAddress(address newAddress) public { if(hasRole(DEFAULT_ADMIN_ROLE, msg.sender)){ address oldAddress = marketing; if(newAddress != oldAddress){ revokeRole(MARKETING, marketing); grantRole(MARKETING, newAddress); marketing = newAddress; _currentBalance[newAddress] = _currentBalance[oldAddress]; _currentBalance[oldAddress] = 0; } } } }
1,256,382
[ 1, 1098, 434, 6138, 364, 25937, 471, 13667, 310, 9230, 2874, 903, 1699, 584, 358, 752, 279, 5232, 434, 2198, 395, 280, 358, 3675, 783, 4463, 11013, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 12022, 8924, 353, 24349, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 565, 533, 1071, 508, 273, 315, 6415, 15020, 12022, 13456, 14432, 203, 565, 1758, 1071, 3410, 31, 203, 203, 565, 2254, 5034, 1071, 15105, 273, 1728, 2826, 6549, 31, 203, 203, 203, 203, 565, 1758, 8526, 3238, 25937, 273, 306, 20, 20029, 23, 5948, 38, 3657, 30454, 4331, 74, 40, 1727, 4033, 8285, 22, 37, 26, 4313, 22, 2163, 37, 29, 40, 25, 4331, 39, 5193, 9676, 23, 16, 374, 92, 25, 71, 21, 39, 29, 7677, 73, 6675, 70, 6162, 4313, 29, 73, 3103, 20, 69, 5193, 70, 7235, 8204, 1611, 24, 74, 22, 2163, 71, 37, 10395, 16, 374, 6554, 2163, 41, 29, 69, 8204, 38, 23, 24347, 2954, 20, 9383, 9599, 41, 70, 42, 2643, 39, 5324, 40, 20, 39, 9803, 69, 41, 20, 6028, 28, 39, 15533, 203, 565, 1758, 3238, 13667, 310, 273, 374, 92, 7132, 2954, 26, 6675, 17374, 26, 6675, 5908, 41, 10689, 72, 21573, 37, 3600, 5324, 6162, 2947, 3657, 9498, 6743, 27, 5482, 31, 203, 565, 2254, 5034, 3238, 2078, 8410, 273, 2130, 31, 203, 203, 565, 2874, 12, 1758, 516, 2254, 5034, 262, 1071, 389, 2972, 13937, 31, 203, 203, 203, 565, 2254, 5034, 1071, 13667, 310, 16936, 2617, 285, 225, 273, 8063, 31, 203, 203, 565, 2254, 5034, 1071, 7433, 9000, 16397, 273, 2078, 8410, 18, 1717, 12, 3355, 21747, 16936, 2617, 285, 1769, 203, 203, 565, 2254, 5034, 1071, 7327, 9535, 4505, 8410, 273, 7433, 2 ]
./full_match/11155111/0x8c49FD4432410E56023F654cbD13eB03411d9c3D/sources/contracts/Contract.sol
assign the contract owner to the registerar
contract certificate { address owner; uint256 public numberOfCertificates = 0; uint256[] certificateKeys; constructor() { owner = msg.sender; } modifier onlyOwner() { require( msg.sender == owner, "Only the registerar can perform this action" ); _; } mapping(uint256 => Certificate) public certificates; mapping(uint256 => bool) lookUp; function addCertificate( string memory _firstName, string memory _middleNames, string memory _lastName, string memory _birthPlace, uint256 _birthDate, uint256 _studentId, string memory _gpa, string memory _school, string memory _degree, string memory _graduationSemester, string memory _merit ) private { if (!lookUp[_studentId]) { certificateKeys.push(_studentId); lookUp[_studentId] = true; revert("Certificate exists"); } Certificate storage cert = certificates[_studentId]; cert.studentId = _studentId; cert.gpa = _gpa; cert.school = _school; cert.degree = _degree; cert.graduationSemester = _graduationSemester; cert.merit = _merit; cert.firstName = _firstName; cert.middleNames = _middleNames; cert.lastName = _lastName; cert.birthPlace = _birthPlace; cert.birthDate = _birthDate; cert.birthDate = cert.birthDate; numberOfCertificates++; } function addCertificate( string memory _firstName, string memory _middleNames, string memory _lastName, string memory _birthPlace, uint256 _birthDate, uint256 _studentId, string memory _gpa, string memory _school, string memory _degree, string memory _graduationSemester, string memory _merit ) private { if (!lookUp[_studentId]) { certificateKeys.push(_studentId); lookUp[_studentId] = true; revert("Certificate exists"); } Certificate storage cert = certificates[_studentId]; cert.studentId = _studentId; cert.gpa = _gpa; cert.school = _school; cert.degree = _degree; cert.graduationSemester = _graduationSemester; cert.merit = _merit; cert.firstName = _firstName; cert.middleNames = _middleNames; cert.lastName = _lastName; cert.birthPlace = _birthPlace; cert.birthDate = _birthDate; cert.birthDate = cert.birthDate; numberOfCertificates++; } } else { function editCertificate( string memory _firstName, string memory _middleNames, string memory _lastName, string memory _birthPlace, uint256 _birthDate, uint256 _studentId, string memory _gpa, string memory _school, string memory _degree, string memory _graduationSemester, string memory _merit ) private { if (!lookUp[_studentId]) { revert("Certificate does not exist"); Certificate memory modCert = Certificate({ firstName: _firstName, middleNames: _middleNames, lastName: _lastName, birthPlace: _birthPlace, birthDate: _birthDate, studentId: certificates[_studentId].studentId, gpa: _gpa, school: _school, degree: _degree, graduationSemester: _graduationSemester, merit: _merit }); certificates[_studentId] = modCert; } } function editCertificate( string memory _firstName, string memory _middleNames, string memory _lastName, string memory _birthPlace, uint256 _birthDate, uint256 _studentId, string memory _gpa, string memory _school, string memory _degree, string memory _graduationSemester, string memory _merit ) private { if (!lookUp[_studentId]) { revert("Certificate does not exist"); Certificate memory modCert = Certificate({ firstName: _firstName, middleNames: _middleNames, lastName: _lastName, birthPlace: _birthPlace, birthDate: _birthDate, studentId: certificates[_studentId].studentId, gpa: _gpa, school: _school, degree: _degree, graduationSemester: _graduationSemester, merit: _merit }); certificates[_studentId] = modCert; } } } else { function editCertificate( string memory _firstName, string memory _middleNames, string memory _lastName, string memory _birthPlace, uint256 _birthDate, uint256 _studentId, string memory _gpa, string memory _school, string memory _degree, string memory _graduationSemester, string memory _merit ) private { if (!lookUp[_studentId]) { revert("Certificate does not exist"); Certificate memory modCert = Certificate({ firstName: _firstName, middleNames: _middleNames, lastName: _lastName, birthPlace: _birthPlace, birthDate: _birthDate, studentId: certificates[_studentId].studentId, gpa: _gpa, school: _school, degree: _degree, graduationSemester: _graduationSemester, merit: _merit }); certificates[_studentId] = modCert; } } function deleteCertificate(uint256 _studentId) private { uint256 _index = 0; if (!lookUp[_studentId]) { revert("Certificate does not exist"); for (uint256 i = 0; i < certificateKeys.length; i++) { if (certificateKeys[i] == _studentId) { _index = i; certificateKeys[_index] = certificateKeys[ certificateKeys.length - 1 ]; certificateKeys.pop(); delete certificates[_studentId]; delete lookUp[_studentId]; numberOfCertificates--; } } } } function deleteCertificate(uint256 _studentId) private { uint256 _index = 0; if (!lookUp[_studentId]) { revert("Certificate does not exist"); for (uint256 i = 0; i < certificateKeys.length; i++) { if (certificateKeys[i] == _studentId) { _index = i; certificateKeys[_index] = certificateKeys[ certificateKeys.length - 1 ]; certificateKeys.pop(); delete certificates[_studentId]; delete lookUp[_studentId]; numberOfCertificates--; } } } } } else { function deleteCertificate(uint256 _studentId) private { uint256 _index = 0; if (!lookUp[_studentId]) { revert("Certificate does not exist"); for (uint256 i = 0; i < certificateKeys.length; i++) { if (certificateKeys[i] == _studentId) { _index = i; certificateKeys[_index] = certificateKeys[ certificateKeys.length - 1 ]; certificateKeys.pop(); delete certificates[_studentId]; delete lookUp[_studentId]; numberOfCertificates--; } } } } function deleteCertificate(uint256 _studentId) private { uint256 _index = 0; if (!lookUp[_studentId]) { revert("Certificate does not exist"); for (uint256 i = 0; i < certificateKeys.length; i++) { if (certificateKeys[i] == _studentId) { _index = i; certificateKeys[_index] = certificateKeys[ certificateKeys.length - 1 ]; certificateKeys.pop(); delete certificates[_studentId]; delete lookUp[_studentId]; numberOfCertificates--; } } } } function getCertificateKeys() public view onlyOwner returns (uint256[] memory) { return certificateKeys; } function getCertificateDataVerifier( uint256 _studentId ) public view returns ( string memory _firstName, string memory _middleNames, string memory _LastName, string memory _gpa, string memory _school, string memory _degree, string memory _graduationSemester ) { if (!lookUp[_studentId]) { revert("Certificate does not exist"); return ( certificates[_studentId].firstName, certificates[_studentId].middleNames, certificates[_studentId].lastName, certificates[_studentId].gpa, certificates[_studentId].school, certificates[_studentId].degree, certificates[_studentId].graduationSemester ); } } function getCertificateDataVerifier( uint256 _studentId ) public view returns ( string memory _firstName, string memory _middleNames, string memory _LastName, string memory _gpa, string memory _school, string memory _degree, string memory _graduationSemester ) { if (!lookUp[_studentId]) { revert("Certificate does not exist"); return ( certificates[_studentId].firstName, certificates[_studentId].middleNames, certificates[_studentId].lastName, certificates[_studentId].gpa, certificates[_studentId].school, certificates[_studentId].degree, certificates[_studentId].graduationSemester ); } } } else { function addCert( string memory _firstName, string memory _middleNames, string memory _lastName, string memory _birthPlace, uint256 _birthDate, uint256 _studentId, string memory _gpa, string memory _school, string memory _degree, string memory _graduationSemester, string memory _merit ) public onlyOwner { addCertificate( _firstName, _middleNames, _lastName, _birthPlace, _birthDate, _studentId, _gpa, _school, _degree, _graduationSemester, _merit ); } function editCert( string memory _firstName, string memory _middleNames, string memory _lastName, string memory _birthPlace, uint256 _birthDate, uint256 _studentId, string memory _gpa, string memory _school, string memory _degree, string memory _graduationSemester, string memory _merit ) public onlyOwner { editCertificate( _firstName, _middleNames, _lastName, _birthPlace, _birthDate, _studentId, _gpa, _school, _degree, _graduationSemester, _merit ); } function delCert(uint256 _studentId) public onlyOwner { deleteCertificate(_studentId); } }
3,835,011
[ 1, 6145, 326, 6835, 3410, 358, 326, 1744, 297, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 4944, 288, 203, 565, 1758, 3410, 31, 203, 565, 2254, 5034, 1071, 7922, 14133, 273, 374, 31, 203, 565, 2254, 5034, 8526, 4944, 2396, 31, 203, 203, 565, 3885, 1435, 288, 203, 3639, 3410, 273, 1234, 18, 15330, 31, 203, 565, 289, 203, 203, 565, 9606, 1338, 5541, 1435, 288, 203, 3639, 2583, 12, 203, 5411, 1234, 18, 15330, 422, 3410, 16, 203, 5411, 315, 3386, 326, 1744, 297, 848, 3073, 333, 1301, 6, 203, 3639, 11272, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 565, 2874, 12, 11890, 5034, 516, 6660, 13, 1071, 12522, 31, 203, 565, 2874, 12, 11890, 5034, 516, 1426, 13, 2324, 1211, 31, 203, 203, 565, 445, 527, 4719, 12, 203, 3639, 533, 3778, 389, 3645, 461, 16, 203, 3639, 533, 3778, 389, 18661, 1557, 16, 203, 3639, 533, 3778, 389, 2722, 461, 16, 203, 3639, 533, 3778, 389, 22531, 6029, 16, 203, 3639, 2254, 5034, 389, 22531, 1626, 16, 203, 3639, 2254, 5034, 389, 26240, 548, 16, 203, 3639, 533, 3778, 389, 6403, 69, 16, 203, 3639, 533, 3778, 389, 28204, 1371, 16, 203, 3639, 533, 3778, 389, 21361, 16, 203, 3639, 533, 3778, 389, 2752, 2544, 367, 13185, 7654, 16, 203, 3639, 533, 3778, 389, 6592, 305, 203, 565, 262, 3238, 288, 203, 3639, 309, 16051, 7330, 1211, 63, 67, 26240, 548, 5717, 288, 203, 5411, 4944, 2396, 18, 6206, 24899, 26240, 548, 1769, 203, 5411, 2324, 1211, 63, 67, 26240, 548, 65, 273, 638, 31, 203, 5411, 15226, 2932, 4719, 1704, 8863, 203, 3639, 2 ]
pragma solidity 0.5.16; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./IStakingContract.sol"; import "./IStakeChangeNotifier.sol"; contract StakingContract is IStakingContract, IMigratableStakingContract { using SafeMath for uint256; struct Stake { uint256 amount; uint256 cooldownAmount; uint256 cooldownEndTime; } struct WithdrawResult { uint256 withdrawnAmount; uint256 stakedAmount; uint256 stakedAmountDiff; } // The version of the smart contract. uint256 public constant VERSION = 1; // The maximum number of approved staking contracts as migration destinations. uint256 public constant MAX_APPROVED_STAKING_CONTRACTS = 10; // The mapping between stake owners and their data. mapping(address => Stake) internal stakes; // Total amount of staked tokens (not including unstaked tokes in cooldown or pending withdrawal). uint256 internal totalStakedTokens; // The period (in seconds) between a stake owner's request to stop staking and being able to withdraw them. uint256 public cooldownPeriodInSec; // The address responsible for managing migration to a new staking contract. address public migrationManager; // The address responsible for emergency operations and graceful return of staked tokens back to their owners. address public emergencyManager; // The list of staking contracts that are approved by this contract. It would be only allowed to migrate a stake to // one of these contracts. IMigratableStakingContract[] public approvedStakingContracts; // The address of the contract responsible for publishing stake change notifications. IStakeChangeNotifier public notifier; // The address of the $EDI Token Contract IERC20 internal token; // Represents whether the contract accepts new staking requests. Please note, that even when it's turned off, // it'd be still possible to unstake or withdraw tokens. // // Note: This can be turned off only once by the emergency manager of the contract. bool public acceptingNewStakes = true; // Represents whether this staking contract allows releasing all unstaked tokens unconditionally. When it's turned // on, stake owners could release their staked tokens, without explicitly requesting to unstake them, and their // previously unstaked tokens, regardless of the cooldown period. This also stops the contract from accepting new // stakes. // // Note: This can be turned off only once by the emergency manager of the contract. bool public releasingAllStakes = false; event MigrationManagerUpdated(address indexed migrationManager); event MigrationDestinationAdded( IMigratableStakingContract indexed stakingContract ); event MigrationDestinationRemoved( IMigratableStakingContract indexed stakingContract ); event EmergencyManagerUpdated(address indexed emergencyManager); event StakeChangeNotifierUpdated(IStakeChangeNotifier indexed notifier); event StoppedAcceptingNewStake(); event ReleasedAllStakes(); modifier onlyMigrationManager() { require( msg.sender == migrationManager, "StakingContract: caller is not the migration manager" ); _; } modifier onlyEmergencyManager() { require( msg.sender == emergencyManager, "StakingContract: caller is not the emergency manager" ); _; } modifier onlyWhenAcceptingNewStakes() { require( acceptingNewStakes && !releasingAllStakes, "StakingContract: not accepting new stakes" ); _; } modifier onlyWhenStakesReleased() { require( releasingAllStakes, "StakingContract: not releasing all stakes" ); _; } modifier onlyWhenStakesNotReleased() { require(!releasingAllStakes, "StakingContract: releasing all stakes"); _; } /// @dev Initializes the staking contract. /// @param _cooldownPeriodInSec uint256 The period (in seconds) between a stake owner's request to stop staking and being /// able to withdraw them. /// @param _migrationManager address The address responsible for managing migration to a new staking contract. /// @param _emergencyManager address The address responsible for emergency operations and graceful return of staked /// tokens back to their owners. /// @param _token IERC20 The address of the $EDI Token constructor( uint256 _cooldownPeriodInSec, address _migrationManager, address _emergencyManager, IERC20 _token ) public { require( _cooldownPeriodInSec > 0, "StakingContract::ctor - cooldown period must be greater than 0" ); require( _migrationManager != address(0), "StakingContract::ctor - migration manager must not be 0" ); require( _emergencyManager != address(0), "StakingContract::ctor - emergency manager must not be 0" ); require( address(_token) != address(0), "StakingContract::ctor - $EDI token must not be 0" ); cooldownPeriodInSec = _cooldownPeriodInSec; migrationManager = _migrationManager; emergencyManager = _emergencyManager; token = _token; } /// @dev Sets the address of the migration manager. /// @param _newMigrationManager address The address of the new migration manager. function setMigrationManager(address _newMigrationManager) external onlyMigrationManager { require( _newMigrationManager != address(0), "StakingContract::setMigrationManager - address must not be 0" ); require( migrationManager != _newMigrationManager, "StakingContract::setMigrationManager - address must be different than the current address" ); migrationManager = _newMigrationManager; emit MigrationManagerUpdated(_newMigrationManager); } /// @dev Sets the address of the emergency manager. /// @param _newEmergencyManager address The address of the new emergency manager. function setEmergencyManager(address _newEmergencyManager) external onlyEmergencyManager { require( _newEmergencyManager != address(0), "StakingContract::setEmergencyManager - address must not be 0" ); require( emergencyManager != _newEmergencyManager, "StakingContract::setEmergencyManager - address must be different than the current address" ); emergencyManager = _newEmergencyManager; emit EmergencyManagerUpdated(_newEmergencyManager); } /// @dev Sets the address of the stake change notifier contract. /// @param _newNotifier IStakeChangeNotifier The address of the new stake change notifier contract. /// /// Note: it's allowed to reset the notifier to a zero address. function setStakeChangeNotifier(IStakeChangeNotifier _newNotifier) external onlyMigrationManager { require( notifier != _newNotifier, "StakingContract::setStakeChangeNotifier - address must be different than the current address" ); notifier = _newNotifier; emit StakeChangeNotifierUpdated(notifier); } /// @dev Adds a new contract to the list of approved staking contracts migration destinations. /// @param _newStakingContract IMigratableStakingContract The new contract to add. function addMigrationDestination( IMigratableStakingContract _newStakingContract ) external onlyMigrationManager { require( address(_newStakingContract) != address(0), "StakingContract::addMigrationDestination - address must not be 0" ); uint256 length = approvedStakingContracts.length; require( length + 1 <= MAX_APPROVED_STAKING_CONTRACTS, "StakingContract::addMigrationDestination - can't add more staking contracts" ); // Check for duplicates. for (uint256 i = 0; i < length; ++i) { require( approvedStakingContracts[i] != _newStakingContract, "StakingContract::addMigrationDestination - can't add a duplicate staking contract" ); } approvedStakingContracts.push(_newStakingContract); emit MigrationDestinationAdded(_newStakingContract); } /// @dev Removes a contract from the list of approved staking contracts migration destinations. /// @param _stakingContract IMigratableStakingContract The contract to remove. function removeMigrationDestination( IMigratableStakingContract _stakingContract ) external onlyMigrationManager { require( address(_stakingContract) != address(0), "StakingContract::removeMigrationDestination - address must not be 0" ); // Check for existence. (uint256 i, bool exists) = findApprovedStakingContractIndex( _stakingContract ); require( exists, "StakingContract::removeMigrationDestination - staking contract doesn't exist" ); // Swap the requested element with the last element and then delete it using pop/ approvedStakingContracts[i] = approvedStakingContracts[approvedStakingContracts .length - 1]; approvedStakingContracts.pop(); emit MigrationDestinationRemoved(_stakingContract); } /// @dev Stakes $EDI tokens on behalf of msg.sender. This method assumes that the user has already approved at least /// the required amount using ERC20 approve. /// @param _amount uint256 The amount of tokens to stake. function stake(uint256 _amount) external onlyWhenAcceptingNewStakes { address stakeOwner = msg.sender; uint256 totalStakedAmount = stake(stakeOwner, _amount); emit Staked(stakeOwner, _amount, totalStakedAmount); // Note: we aren't concerned with reentrancy since: // 1. At this point, due to the CEI pattern, a reentrant notifier can't affect the effects of this method. // 2. The notifier is set and managed by the migration manager. stakeChange(stakeOwner, _amount, true, totalStakedAmount); } /// @dev Unstakes $EDI tokens from msg.sender. If successful, this will start the cooldown period, after which /// msg.sender would be able to withdraw all of his tokens. /// @param _amount uint256 The amount of tokens to unstake. function unstake(uint256 _amount) external { require( _amount > 0, "StakingContract::unstake - amount must be greater than 0" ); address stakeOwner = msg.sender; Stake storage stakeData = stakes[stakeOwner]; uint256 stakedAmount = stakeData.amount; uint256 cooldownAmount = stakeData.cooldownAmount; uint256 cooldownEndTime = stakeData.cooldownEndTime; require( _amount <= stakedAmount, "StakingContract::unstake - can't unstake more than the current stake" ); // If any tokens in cooldown are ready for withdrawal - revert. Stake owner should withdraw their unstaked // tokens first. require( cooldownAmount == 0 || cooldownEndTime > now, "StakingContract::unstake - unable to unstake when there are tokens pending withdrawal" ); // Update the amount of tokens in cooldown. Please note that this will also restart the cooldown period of all // tokens in cooldown. stakeData.amount = stakedAmount.sub(_amount); stakeData.cooldownAmount = cooldownAmount.add(_amount); stakeData.cooldownEndTime = now.add(cooldownPeriodInSec); totalStakedTokens = totalStakedTokens.sub(_amount); uint256 totalStakedAmount = stakeData.amount; emit Unstaked(stakeOwner, _amount, totalStakedAmount); // Note: we aren't concerned with reentrancy since: // 1. At this point, due to the CEI pattern, a reentrant notifier can't affect the effects of this method. // 2. The notifier is set and managed by the migration manager. stakeChange(stakeOwner, _amount, false, totalStakedAmount); } /// @dev Requests to withdraw all of staked $EDI tokens back to msg.sender. Stake owners can withdraw their $EDI /// tokens only after previously unstaking them and after the cooldown period has passed (unless the contract was /// requested to release all stakes). function withdraw() external { address stakeOwner = msg.sender; WithdrawResult memory res = withdraw(stakeOwner); emit Withdrew(stakeOwner, res.withdrawnAmount, res.stakedAmount); // Trigger staking state change notifications only if the staking amount was changed. if (res.stakedAmountDiff == 0) { return; } // Note: we aren't concerned with reentrancy since: // 1. At this point, due to the CEI pattern, a reentrant notifier can't affect the effects of this method. // 2. The notifier is set and managed by the migration manager. stakeChange(stakeOwner, res.stakedAmountDiff, false, res.stakedAmount); } /// @dev Restakes unstaked $EDI tokens (in or after cooldown) for msg.sender. function restake() external onlyWhenAcceptingNewStakes { address stakeOwner = msg.sender; Stake storage stakeData = stakes[stakeOwner]; uint256 cooldownAmount = stakeData.cooldownAmount; require( cooldownAmount > 0, "StakingContract::restake - no unstaked tokens" ); stakeData.amount = stakeData.amount.add(cooldownAmount); stakeData.cooldownAmount = 0; stakeData.cooldownEndTime = 0; totalStakedTokens = totalStakedTokens.add(cooldownAmount); uint256 totalStakedAmount = stakeData.amount; emit Restaked(stakeOwner, cooldownAmount, totalStakedAmount); // Note: we aren't concerned with reentrancy since: // 1. At this point, due to the CEI pattern, a reentrant notifier can't affect the effects of this method. // 2. The notifier is set and managed by the migration manager. stakeChange(stakeOwner, cooldownAmount, true, totalStakedAmount); } /// @dev Stakes $EDI tokens on behalf of msg.sender. This method assumes that the user has already approved at least /// the required amount using ERC20 approve. /// @param _stakeOwner address The specified stake owner. /// @param _amount uint256 The amount of tokens to stake. function acceptMigration(address _stakeOwner, uint256 _amount) external onlyWhenAcceptingNewStakes { uint256 totalStakedAmount = stake(_stakeOwner, _amount); emit AcceptedMigration(_stakeOwner, _amount, totalStakedAmount); // Note: we aren't concerned with reentrancy since: // 1. At this point, due to the CEI pattern, a reentrant notifier can't affect the effects of this method. // 2. The notifier is set and managed by the migration manager. stakeChange(_stakeOwner, _amount, true, totalStakedAmount); } /// @dev Migrates the stake of msg.sender from this staking contract to a new approved staking contract. /// @param _newStakingContract IMigratableStakingContract The new staking contract which supports stake migration. /// @param _amount uint256 The amount of tokens to migrate. function migrateStakedTokens( IMigratableStakingContract _newStakingContract, uint256 _amount ) external onlyWhenStakesNotReleased { require( isApprovedStakingContract(_newStakingContract), "StakingContract::migrateStakedTokens - migration destination wasn't approved" ); require( _amount > 0, "StakingContract::migrateStakedTokens - amount must be greater than 0" ); address stakeOwner = msg.sender; Stake storage stakeData = stakes[stakeOwner]; uint256 stakedAmount = stakeData.amount; require( stakedAmount > 0, "StakingContract::migrateStakedTokens - no staked tokens" ); require( _amount <= stakedAmount, "StakingContract::migrateStakedTokens - amount exceeds staked token balance" ); stakeData.amount = stakedAmount.sub(_amount); totalStakedTokens = totalStakedTokens.sub(_amount); require( _newStakingContract.getToken() == token, "StakingContract::migrateStakedTokens - staked tokens must be the same" ); require( token.approve(address(_newStakingContract), _amount), "StakingContract::migrateStakedTokens - couldn't approve transfer" ); emit MigratedStake(stakeOwner, _amount, stakeData.amount); _newStakingContract.acceptMigration(stakeOwner, _amount); // Note: we aren't concerned with reentrancy since: // 1. At this point, due to the CEI pattern, a reentrant notifier can't affect the effects of this method. // 2. The notifier is set and managed by the migration manager. stakeMigration(stakeOwner, _amount); } /// @dev Distributes staking rewards to a list of addresses by directly adding rewards to their stakes. This method /// assumes that the user has already approved at least the required amount using ERC20 approve. Since this is a /// convenience method, we aren't concerned about reaching block gas limit by using large lists. We assume that /// callers will be able to batch/paginate their requests properly. /// @param _totalAmount uint256 The total amount of rewards to distributes. /// @param _stakeOwners address[] The addresses of the stake owners. /// @param _amounts uint256[] The amounts of the rewards. function distributeRewards( uint256 _totalAmount, address[] calldata _stakeOwners, uint256[] calldata _amounts ) external onlyWhenAcceptingNewStakes { require( _totalAmount > 0, "StakingContract::distributeRewards - total amount must be greater than 0" ); uint256 stakeOwnersLength = _stakeOwners.length; uint256 amountsLength = _amounts.length; require( stakeOwnersLength > 0 && amountsLength > 0, "StakingContract::distributeRewards - lists can't be empty" ); require( stakeOwnersLength == amountsLength, "StakingContract::distributeRewards - lists must be of the same size" ); // Transfer all the tokens to the smart contract and update the stake owners list accordingly. require( token.transferFrom(msg.sender, address(this), _totalAmount), "StakingContract::distributeRewards - insufficient allowance" ); bool[] memory signs = new bool[](amountsLength); uint256[] memory totalStakedAmounts = new uint256[](amountsLength); uint256 expectedTotalAmount = 0; for (uint256 i = 0; i < stakeOwnersLength; ++i) { address stakeOwner = _stakeOwners[i]; uint256 amount = _amounts[i]; require( stakeOwner != address(0), "StakingContract::distributeRewards - stake owner can't be 0" ); require( amount > 0, "StakingContract::distributeRewards - amount must be greater than 0" ); Stake storage stakeData = stakes[stakeOwner]; stakeData.amount = stakeData.amount.add(amount); expectedTotalAmount = expectedTotalAmount.add(amount); uint256 totalStakedAmount = stakeData.amount; signs[i] = true; totalStakedAmounts[i] = totalStakedAmount; emit Staked(stakeOwner, amount, totalStakedAmount); } require( _totalAmount == expectedTotalAmount, "StakingContract::distributeRewards - incorrect total amount" ); totalStakedTokens = totalStakedTokens.add(_totalAmount); // Note: we aren't concerned with reentrancy since: // 1. At this point, due to the CEI pattern, a reentrant notifier can't affect the effects of this method. // 2. The notifier is set and managed by the migration manager. stakeChangeBatch(_stakeOwners, _amounts, signs, totalStakedAmounts); } /// @dev Returns the stake of the specified stake owner (excluding unstaked tokens). /// @param _stakeOwner address The address to check. /// @return uint256 The stake of the stake owner. function getStakeBalanceOf(address _stakeOwner) external view returns (uint256) { return stakes[_stakeOwner].amount; } /// @dev Returns the total amount staked tokens (excluding unstaked tokens). /// @return uint256 The total staked tokens of all stake owners. function getTotalStakedTokens() external view returns (uint256) { return totalStakedTokens; } /// @dev Returns the time that the cooldown period ends (or ended) and the amount of tokens to be released. /// @param _stakeOwner address The address to check. /// @return cooldownAmount uint256 The total tokens in cooldown. /// @return cooldownEndTime uint256 The time when the cooldown period ends (in seconds). function getUnstakeStatus(address _stakeOwner) external view returns (uint256 cooldownAmount, uint256 cooldownEndTime) { Stake memory stakeData = stakes[_stakeOwner]; cooldownAmount = stakeData.cooldownAmount; cooldownEndTime = stakeData.cooldownEndTime; } /// @dev Returns the address of the underlying staked token. /// @return IERC20 The address of the token. function getToken() external view returns (IERC20) { return token; } /// @dev Requests the contract to stop accepting new staking requests. function stopAcceptingNewStakes() external onlyEmergencyManager onlyWhenAcceptingNewStakes { acceptingNewStakes = false; emit StoppedAcceptingNewStake(); } /// @dev Requests the contract to release all stakes. function releaseAllStakes() external onlyEmergencyManager onlyWhenStakesNotReleased { releasingAllStakes = true; emit ReleasedAllStakes(); } /// @dev Requests withdraw of released tokens for a list of addresses. /// @param _stakeOwners address[] The addresses of the stake owners. function withdrawReleasedStakes(address[] calldata _stakeOwners) external onlyWhenStakesReleased { uint256 stakeOwnersLength = _stakeOwners.length; uint256[] memory stakedAmountDiffs = new uint256[](stakeOwnersLength); bool[] memory signs = new bool[](stakeOwnersLength); uint256[] memory totalStakedAmounts = new uint256[](stakeOwnersLength); for (uint256 i = 0; i < stakeOwnersLength; ++i) { address stakeOwner = _stakeOwners[i]; WithdrawResult memory res = withdraw(stakeOwner); stakedAmountDiffs[i] = res.stakedAmountDiff; signs[i] = false; totalStakedAmounts[i] = res.stakedAmount; emit Withdrew(stakeOwner, res.withdrawnAmount, res.stakedAmount); } // Note: we aren't concerned with reentrancy since: // 1. At this point, due to the CEI pattern, a reentrant notifier can't affect the effects of this method. // 2. The notifier is set and managed by the migration manager. stakeChangeBatch( _stakeOwners, stakedAmountDiffs, signs, totalStakedAmounts ); } /// @dev Returns whether a specific staking contract was approved as a migration destination. /// @param _stakingContract IMigratableStakingContract The staking contract to look for. /// @return exists bool The approval status. function isApprovedStakingContract( IMigratableStakingContract _stakingContract ) public view returns (bool exists) { (, exists) = findApprovedStakingContractIndex(_stakingContract); } /// @dev Returns whether stake change notification is enabled. function shouldNotifyStakeChange() internal view returns (bool) { return address(notifier) != address(0); } /// @dev Notifies of stake change events. /// @param _stakeOwner address The address of the subject stake owner. /// @param _amount int256 The difference in the total staked amount. /// @param _sign bool The sign of the added (true) or subtracted (false) amount. /// @param _updatedStake uint256 The updated total staked amount. function stakeChange( address _stakeOwner, uint256 _amount, bool _sign, uint256 _updatedStake ) internal { if (!shouldNotifyStakeChange()) { return; } notifier.stakeChange(_stakeOwner, _amount, _sign, _updatedStake); } /// @dev Notifies of multiple stake change events. /// @param _stakeOwners address[] The addresses of subject stake owners. /// @param _amounts uint256[] The differences in total staked amounts. /// @param _signs bool[] The signs of the added (true) or subtracted (false) amounts. /// @param _updatedStakes uint256[] The updated total staked amounts. function stakeChangeBatch( address[] memory _stakeOwners, uint256[] memory _amounts, bool[] memory _signs, uint256[] memory _updatedStakes ) internal { if (!shouldNotifyStakeChange()) { return; } notifier.stakeChangeBatch( _stakeOwners, _amounts, _signs, _updatedStakes ); } /// @dev Notifies of stake migration event. /// @param _stakeOwner address The address of the subject stake owner. /// @param _amount uint256 The migrated amount. function stakeMigration(address _stakeOwner, uint256 _amount) internal { if (!shouldNotifyStakeChange()) { return; } notifier.stakeMigration(_stakeOwner, _amount); } /// @dev Stakes amount of $EDI tokens on behalf of the specified stake owner. /// @param _stakeOwner address The specified stake owner. /// @param _amount uint256 The amount of tokens to stake. /// @return totalStakedAmount uint256 The total stake of the stake owner. function stake(address _stakeOwner, uint256 _amount) private returns (uint256 totalStakedAmount) { require( _stakeOwner != address(0), "StakingContract::stake - stake owner can't be 0" ); require( _amount > 0, "StakingContract::stake - amount must be greater than 0" ); Stake storage stakeData = stakes[_stakeOwner]; stakeData.amount = stakeData.amount.add(_amount); totalStakedTokens = totalStakedTokens.add(_amount); totalStakedAmount = stakeData.amount; // Transfer the tokens to the smart contract and update the stake owners list accordingly. require( token.transferFrom(msg.sender, address(this), _amount), "StakingContract::stake - insufficient allowance" ); } /// @dev Requests to withdraw all of staked $EDI tokens back to the specified stake owner. Stake owners can withdraw /// their $EDI tokens only after previously unstaking them and after the cooldown period has passed (unless the /// contract was requested to release all stakes). /// @return res WithdrawResult The result of the withdraw operation. function withdraw(address _stakeOwner) private returns (WithdrawResult memory res) { require( _stakeOwner != address(0), "StakingContract::withdraw - stake owner can't be 0" ); Stake storage stakeData = stakes[_stakeOwner]; res.stakedAmount = stakeData.amount; res.withdrawnAmount = stakeData.cooldownAmount; res.stakedAmountDiff = 0; if (!releasingAllStakes) { require( res.withdrawnAmount > 0, "StakingContract::withdraw - no unstaked tokens" ); require( stakeData.cooldownEndTime <= now, "StakingContract::withdraw - tokens are still in cooldown" ); } else { // If the contract was requested to release all stakes - allow to withdraw all staked and unstaked tokens. res.withdrawnAmount = res.withdrawnAmount.add(res.stakedAmount); res.stakedAmountDiff = res.stakedAmount; require( res.withdrawnAmount > 0, "StakingContract::withdraw - no staked or unstaked tokens" ); stakeData.amount = 0; totalStakedTokens = totalStakedTokens.sub(res.stakedAmount); res.stakedAmount = 0; } stakeData.cooldownAmount = 0; stakeData.cooldownEndTime = 0; require( token.transfer(_stakeOwner, res.withdrawnAmount), "StakingContract::withdraw - couldn't transfer stake" ); } /// @dev Returns an index of an existing approved staking contract. /// @param _stakingContract IMigratableStakingContract The staking contract to look for. /// @return index uint The index of the located staking contract (in the case that it was found). /// @return exists bool The search result. function findApprovedStakingContractIndex( IMigratableStakingContract _stakingContract ) private view returns (uint256 index, bool exists) { uint256 length = approvedStakingContracts.length; for (index = 0; index < length; ++index) { if (approvedStakingContracts[index] == _stakingContract) { exists = true; return (index, exists); } } exists = false; } }
Represents whether the contract accepts new staking requests. Please note, that even when it's turned off, it'd be still possible to unstake or withdraw tokens. Note: This can be turned off only once by the emergency manager of the contract.
bool public acceptingNewStakes = true;
1,815,869
[ 1, 23869, 87, 2856, 326, 6835, 8104, 394, 384, 6159, 3285, 18, 7801, 4721, 16, 716, 5456, 1347, 518, 1807, 21826, 3397, 16, 518, 14271, 506, 4859, 3323, 358, 640, 334, 911, 578, 598, 9446, 2430, 18, 3609, 30, 1220, 848, 506, 21826, 3397, 1338, 3647, 635, 326, 801, 24530, 3301, 434, 326, 6835, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 1426, 1071, 25806, 1908, 510, 3223, 273, 638, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import "./utils/BaseTest.sol"; import "./utils/mocks/MockERC721A.sol"; // import "solmate/test/ERC721.t.sol"; /// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/test/ERC721.t.sol) contract ERC721Recipient is ERC721TokenReceiver { function onERC721Received( address, address, uint256, bytes calldata ) public virtual override returns (bytes4) { return ERC721TokenReceiver.onERC721Received.selector; } } /// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/test/ERC721.t.sol) contract RevertingERC721Recipient is ERC721TokenReceiver { function onERC721Received( address, address, uint256, bytes calldata ) public virtual override returns (bytes4) { revert(string(abi.encodePacked(ERC721TokenReceiver.onERC721Received.selector))); } } /// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/test/ERC721.t.sol) contract WrongReturnDataERC721Recipient is ERC721TokenReceiver { function onERC721Received( address, address, uint256, bytes calldata ) public virtual override returns (bytes4) { return 0x12345678; } } /// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/test/ERC721.t.sol) contract NonERC721Recipient { string public gm = "gm"; } contract TestERC721A is BaseTest { MockERC721A internal erc721a; function setUp() public virtual { erc721a = new MockERC721A(); vm.label(address(erc721a), "ERC721A"); vm.label(address(this), "TestERC721A"); } function invariant_metadata() public { assertEq(erc721a.name(), "TestName"); assertEq(erc721a.symbol(), "TestSymbol"); } function test_mint() public { erc721a.mint(alice, 1); assertEq(erc721a.balanceOf(alice), 1); assertEq(erc721a.totalSupply(), 1); assertEq(erc721a.ownerOf(1), alice); } function testFail_mint_toAddressZero() public { // vm.expectRevert(ERC721A.InvalidRecipient.selector); erc721a.mint(address(0), 1); } function testFail_mint_amountZero() public { // vm.expectRevert(ERC721A.InvalidAmount.selector); erc721a.mint(alice, 0); } function test_safeMint_toEOA() public { erc721a.safeMint(alice, 1); assertEq(erc721a.balanceOf(alice), 1); assertEq(erc721a.ownerOf(1), alice); } function test_safeMint_toERC721Recipient() public { vm.etch(alice, type(ERC721Recipient).runtimeCode); vm.expectCall( alice, abi.encodeWithSignature( "onERC721Received(address,address,uint256,bytes)", address(this), address(0), 1, "TestData" ) ); erc721a.safeMint(alice, 1, "TestData"); assertEq(erc721a.balanceOf(alice), 1); assertEq(erc721a.ownerOf(1), alice); } function testFail_safeMint_toRevertingERC721Recipient() public { vm.etch(alice, type(RevertingERC721Recipient).runtimeCode); // vm.expectRevert(ERC721A.UnsafeRecipient.selector); erc721a.safeMint(alice, 1); } function test_totalSupply() public { assertEq(erc721a.totalSupply(), 0); erc721a.mint(alice, 1); assertEq(erc721a.totalSupply(), 1); } function test_tokenOfOwnerByIndex() public { erc721a.mint(alice, 1); assertEq(erc721a.tokenOfOwnerByIndex(alice, 0), 1); } function testFail_tokenOfOwnerByIndex_unMinted() public view { // vm.expectRevert(ERC721A.InvalidIndex.selector); erc721a.tokenOfOwnerByIndex(alice, 0); } function test_tokenByIndex() public { erc721a.mint(alice, 1); assertEq(erc721a.tokenByIndex(1), 1); } function testFail_tokenByIndex_invalidIndex() public view { // vm.expectRevert(ERC721A.InvalidIndex.selector); erc721a.tokenByIndex(0); } function testFail_tokenByIndex_unMinted() public view { // vm.expectRevert(ERC721A.InvalidIndex.selector); erc721a.tokenByIndex(1); } function test_balanceOf() public { assertEq(erc721a.balanceOf(alice), 0); erc721a.mint(alice, 1); assertEq(erc721a.balanceOf(alice), 1); } function testFail_balanceOf_addressZero() public view { // vm.expectRevert(ERC721A.InvalidOwner.selector); erc721a.balanceOf(address(0)); } function test_ownerOf() public { erc721a.mint(alice, 1); assertEq(erc721a.ownerOf(1), alice); } function testFail_ownerOf_nonExistentToken() public view { // vm.expectRevert(ERC721.NonExistentToken.selector); erc721a.ownerOf(0); } function testFail_ownerOf_unMinted() public view { // vm.expectRevert(ERC721.NonExistentToken.selector); erc721a.ownerOf(1); } function test_transferFrom() public { erc721a.mint(alice, 1); vm.prank(alice); erc721a.approve(bob, 1); vm.prank(bob); erc721a.transferFrom(alice, bob, 1); assertEq(erc721a.getApproved(1), address(0)); assertEq(erc721a.balanceOf(alice), 0); assertEq(erc721a.balanceOf(bob), 1); assertEq(erc721a.ownerOf(1), bob); } function test_transferFrom_self() public { erc721a.mint(alice, 1); vm.prank(alice); erc721a.transferFrom(alice, bob, 1); assertEq(erc721a.balanceOf(alice), 0); assertEq(erc721a.balanceOf(bob), 1); assertEq(erc721a.ownerOf(1), bob); } function testFail_transferFrom_invalidToken() public { // vm.expectRevert(ERC721.NonExistentToken.selector); erc721a.transferFrom(alice, bob, 0); } function testFail_transferFrom_unMinted() public { // vm.expectRevert(ERC721.NonExistentToken.selector); erc721a.transferFrom(alice, bob, 1); } function testFail_transferFrom_wrongFrom() public { erc721a.mint(address(123), 1); // vm.expectRevert(ERC721.WrongFrom.selector); erc721a.transferFrom(alice, bob, 1); } function testFail_transferFrom_unAuthorized() public { erc721a.mint(alice, 1); vm.prank(bob); erc721a.transferFrom(alice, bob, 1); } function testFail_transferFrom_toAddressZero() public { erc721a.mint(alice, 1); vm.prank(alice); // vm.expectRevert(ERC721.InvalidRecipient.selector); erc721a.transferFrom(alice, address(0), 1); } function test_safeTransferFrom() public { vm.startPrank(alice); uint256 id = 1; erc721a.mint(alice, 1); vm.expectCall( address(this), abi.encodeWithSignature( "onERC721Received(address,address,uint256,bytes)", alice, alice, id, "" ) ); erc721a.safeTransferFrom(alice, address(this), id); } function test_approve() public { erc721a.mint(alice, 1); vm.prank(alice); erc721a.approve(bob, 1); assertEq(erc721a.getApproved(1), bob); } function testFail_approve_invalidToken() public { vm.prank(alice); erc721a.approve(bob, 0); } function testFail_approve_unMinted() public { vm.prank(alice); erc721a.approve(bob, 1); } function test_setApprovalForAll() public { vm.startPrank(alice); erc721a.setApprovalForAll(bob, true); assertTrue(erc721a.isApprovedForAll(alice, bob)); erc721a.setApprovalForAll(bob, false); assertFalse(erc721a.isApprovedForAll(alice, bob)); } function testFuzz_mint(address to, uint8 amount) public { vm.assume(to != address(0) && amount != 0 && amount <= 10); erc721a.mint(to, amount); assertEq(erc721a.balanceOf(to), amount); assertEq(erc721a.totalSupply(), amount); for (uint256 i; i < amount; i++) { assertEq(erc721a.ownerOf(i + 1), to); } } function testFailFuzz_mint_toAddressZero(uint128 amount) public { vm.assume(amount != 0); // vm.expectRevert(ERC721A.InvalidRecipient.selector); erc721a.mint(address(0), amount); } function testFailFuzz_mint_amountZero(address to) public { vm.assume(to != address(0)); // vm.expectRevert(ERC721A.InvalidAmount.selector); erc721a.mint(to, 0); } function testFuzz_safeMint_toEOA(address to, uint8 amount) public { vm.assume(to != address(0) && amount != 0 && amount <= 10); erc721a.safeMint(to, amount); assertEq(erc721a.balanceOf(to), amount); for (uint256 i; i < amount; i++) { assertEq(erc721a.ownerOf(i + 1), to); } } function testFuzz_safeMint_toERC721Recipient( address to, uint8 amount, bytes calldata data ) public { vm.assume(to != address(0) && amount != 0 && amount <= 10); vm.etch(to, type(ERC721Recipient).runtimeCode); for (uint256 i; i < amount; i++) { vm.expectCall( to, abi.encodeWithSignature( "onERC721Received(address,address,uint256,bytes)", address(this), address(0), i + 1, data ) ); } erc721a.safeMint(to, amount, data); assertEq(erc721a.balanceOf(to), amount); for (uint256 i; i < amount; i++) { assertEq(erc721a.ownerOf(i + 1), to); } } function testFailFuzz_safeMint_toRevertingERC721Recipient(address to, uint128 amount) public { vm.assume(to != address(0) && amount != 0); vm.etch(to, type(RevertingERC721Recipient).runtimeCode); // vm.expectRevert(ERC721A.UnsafeRecipient.selector); erc721a.safeMint(to, amount); } function testFuzz_tokenOfOwnerByIndex(address owner, uint8 amount) public { vm.assume(owner != address(0) && amount != 0 && amount <= 10); erc721a.mint(owner, amount); for (uint256 i; i < amount; i++) { assertEq(erc721a.tokenOfOwnerByIndex(owner, i), i + 1); } } function testFailFuzz_tokenOfOwnerByIndex_unMinted(address owner, uint256 idx) public { vm.assume(owner != address(0) && idx != 0); erc721a.tokenOfOwnerByIndex(owner, idx); } function testFuzz_tokenByIndex(address rnd, uint8 amount) public { vm.assume(rnd != address(0) && amount != 0 && amount <= 10); erc721a.mint(rnd, amount); for (uint256 i; i < amount; i++) { assertEq(erc721a.tokenByIndex(i + 1), i + 1); } } function testFailFuzz_tokenByIndex_unMinted(uint256 id) public { vm.assume(id != 0); erc721a.tokenByIndex(id); } function testFailFuzz_ownerOf_unMinted(uint256 id) public { vm.assume(id != 0); erc721a.ownerOf(id); } function testFuzz_transferFrom( address from, address to, address operator, uint8 amount ) public { vm.assume( from != address(0) && to != address(0) && from != to && from != operator && operator != to && amount != 0 && amount <= 10 ); erc721a.mint(from, amount); for (uint256 i; i < amount; i++) { uint256 id = i + 1; vm.prank(from); erc721a.approve(operator, id); vm.prank(operator); erc721a.transferFrom(from, to, id); assertEq(erc721a.getApproved(id), address(0)); assertEq(erc721a.ownerOf(id), to); } assertEq(erc721a.balanceOf(from), 0); assertEq(erc721a.balanceOf(to), amount); } function testFuzz_transferFrom_self( address from, address to, uint8 amount ) public { vm.assume( from != address(0) && to != address(0) && from != to && amount != 0 && amount <= 10 ); erc721a.mint(from, amount); vm.startPrank(from); for (uint256 i; i < amount; i++) { erc721a.transferFrom(from, to, i + 1); } vm.stopPrank(); assertEq(erc721a.balanceOf(from), 0); assertEq(erc721a.balanceOf(to), amount); for (uint256 i; i < amount; i++) { assertEq(erc721a.ownerOf(i + 1), to); } } function testFailFuzz_transferFrom_invalidToken(address from, address to) public { vm.assume(from != address(0) && to != address(0) && from != to); erc721a.transferFrom(from, to, 0); } function testFailFuzz_transferFrom_unMinted( address from, address to, uint256 id ) public { vm.assume(from != address(0) && to != address(0) && from != to && id != 0); erc721a.transferFrom(from, to, id); } function testFailFuzz_transferFrom_wrongFrom( address from, address to, address rnd ) public { vm.assume( from != address(0) && to != address(0) && rnd != address(0) && from != to && from != rnd && rnd != to ); erc721a.mint(rnd, 1); erc721a.transferFrom(from, to, 1); } function testFailFuzz_transferFrom_unAuthorized(address from, address to) public { vm.assume(from != address(0) && to != address(0) && from != to); erc721a.mint(from, 1); vm.prank(to); erc721a.transferFrom(from, to, 1); } function testFailFuzz_transferFrom_toAddressZero(address from) public { vm.assume(from != address(0)); erc721a.mint(from, 1); vm.prank(from); erc721a.transferFrom(from, address(0), 1); } function testFuzz_safeTransferFrom( address from, address to, uint8 amount, bytes calldata data ) public { vm.assume( from != address(0) && to != address(0) && from != to && amount != 0 && amount <= 10 ); vm.etch(to, type(ERC721Recipient).runtimeCode); erc721a.mint(from, amount); vm.startPrank(from); for (uint256 i; i < amount; i++) { uint256 id = i + 1; vm.expectCall( to, abi.encodeWithSignature( "onERC721Received(address,address,uint256,bytes)", from, from, id, data ) ); erc721a.safeTransferFrom(from, to, id, data); } vm.stopPrank(); assertEq(erc721a.balanceOf(to), amount); for (uint256 i; i < amount; i++) { assertEq(erc721a.ownerOf(i + 1), to); } } function testFuzz_approve( address from, address spender, uint8 amount ) public { vm.assume( from != address(0) && spender != address(0) && from != spender && amount != 0 && amount <= 10 ); erc721a.mint(from, amount); uint256 id = (getRandom256(amount) % amount) + 1; vm.prank(from); erc721a.approve(spender, id); assertEq(erc721a.getApproved(id), spender); } function testFailFuzz_approve_invalidToken(address from, address spender) public { vm.assume(from != address(0) && spender != address(0) && from != spender); vm.prank(from); erc721a.approve(spender, 0); } function testFailFuzz_approve_unMinted( address from, address spender, uint256 id ) public { vm.assume(from != address(0) && spender != address(0) && from != spender && id != 0); vm.prank(from); erc721a.approve(spender, id); } function testFuzz_setApprovalForAll( address from, address spender, bool approved ) public { vm.assume(from != address(0) && spender != address(0) && from != spender); vm.startPrank(from); erc721a.setApprovalForAll(spender, approved); assertBoolEq(erc721a.isApprovedForAll(from, spender), approved); } function testGas_deploy() public { unchecked { new MockERC721A(); } } function testGas_mint() public { // start slots warm startMeasuringGas("First mint"); erc721a.mint(address(69), 1); stopMeasuringGas(); startMeasuringGas("Mint 1"); erc721a.mint(address(1), 1); stopMeasuringGas(); startMeasuringGas("Mint 2"); erc721a.mint(address(2), 2); stopMeasuringGas(); startMeasuringGas("Mint 3"); erc721a.mint(address(3), 3); stopMeasuringGas(); startMeasuringGas("Mint 4"); erc721a.mint(address(4), 4); stopMeasuringGas(); startMeasuringGas("Mint 5"); erc721a.mint(address(5), 5); stopMeasuringGas(); startMeasuringGas("Mint 10"); erc721a.mint(address(10), 10); stopMeasuringGas(); } function testGas_safeMint() public { // start slots warm startMeasuringGas("First mint"); erc721a.safeMint(address(69), 1); stopMeasuringGas(); startMeasuringGas("Mint 1"); erc721a.safeMint(address(1), 1); stopMeasuringGas(); startMeasuringGas("Mint 2"); erc721a.safeMint(address(2), 2); stopMeasuringGas(); startMeasuringGas("Mint 3"); erc721a.safeMint(address(3), 3); stopMeasuringGas(); startMeasuringGas("Mint 4"); erc721a.safeMint(address(4), 4); stopMeasuringGas(); startMeasuringGas("Mint 5"); erc721a.safeMint(address(5), 5); stopMeasuringGas(); startMeasuringGas("Mint 10"); erc721a.safeMint(address(10), 10); stopMeasuringGas(); } function testGas_transferFrom() public { vm.startPrank(alice); erc721a.mint(alice, 2); startMeasuringGas("First transfer"); erc721a.transferFrom(alice, bob, 1); stopMeasuringGas(); startMeasuringGas("Second transfer"); erc721a.transferFrom(alice, bob, 2); stopMeasuringGas(); } function testGas_safeTransferFrom() public { vm.startPrank(alice); erc721a.mint(alice, 2); startMeasuringGas("First transfer"); erc721a.safeTransferFrom(alice, bob, 1); stopMeasuringGas(); startMeasuringGas("Second transfer"); erc721a.safeTransferFrom(alice, bob, 2); stopMeasuringGas(); } }
vm.expectRevert(ERC721A.InvalidAmount.selector);
function testFail_mint_amountZero() public { erc721a.mint(alice, 0); }
15,866,372
[ 1, 3489, 18, 12339, 426, 1097, 12, 654, 39, 27, 5340, 37, 18, 1941, 6275, 18, 9663, 1769, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 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, 1842, 3754, 67, 81, 474, 67, 8949, 7170, 1435, 1071, 288, 203, 3639, 6445, 71, 27, 5340, 69, 18, 81, 474, 12, 287, 1812, 16, 374, 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 ]
./full_match/5/0x08fA73274Dc7EF3Eb0CDBb5D6D07C8454cD48b5A/sources/_superfluid-finance/ethereum-contracts/contracts/interfaces/superfluid/Definitions.sol
Validate configWord cleaness for future compatibility, or else may introduce undefined future behavior
function isConfigWordClean(uint256 configWord) internal pure returns (bool) { return (configWord & ~(APP_LEVEL_MASK | APP_JAIL_BIT | AGREEMENT_CALLBACK_NOOP_BITMASKS)) == uint256(0); }
1,890,005
[ 1, 4270, 642, 3944, 2721, 403, 364, 3563, 8926, 16, 578, 469, 2026, 16658, 311, 3109, 3563, 6885, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 353, 809, 3944, 7605, 12, 11890, 5034, 642, 3944, 13, 2713, 16618, 1135, 261, 6430, 13, 288, 203, 3639, 327, 261, 1425, 3944, 473, 4871, 12, 7215, 67, 10398, 67, 11704, 571, 9146, 67, 46, 6575, 67, 15650, 571, 432, 43, 9719, 3212, 67, 30312, 67, 3417, 3665, 67, 15650, 11704, 55, 3719, 422, 2254, 5034, 12, 20, 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 ]
// SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../../internal/valuation/ExchangeRate.sol"; import "../../internal/markets/CashGroup.sol"; import "../../internal/nTokenHandler.sol"; import "../../internal/balances/TokenHandler.sol"; import "../../global/StorageLayoutV1.sol"; import "../../global/LibStorage.sol"; import "../../global/Types.sol"; import "../../proxy/utils/UUPSUpgradeable.sol"; import "../adapters/nTokenERC20Proxy.sol"; import "interfaces/notional/AssetRateAdapter.sol"; import "interfaces/chainlink/AggregatorV2V3Interface.sol"; import "interfaces/notional/NotionalGovernance.sol"; import "interfaces/notional/nTokenERC20.sol"; import "@openzeppelin/contracts/utils/Address.sol"; /// @notice Governance methods can only be called by the governance contract contract GovernanceAction is StorageLayoutV1, NotionalGovernance, UUPSUpgradeable { /// @dev Throws if called by any account other than the owner. modifier onlyOwner() { require(owner == msg.sender, "Ownable: caller is not the owner"); _; } function _checkValidCurrency(uint16 currencyId) internal view { require(0 < currencyId && currencyId <= maxCurrencyId, "Invalid currency id"); } /// @dev Transfers ownership of the contract to a new account (`newOwner`). /// Can only be called by the current owner. function transferOwnership(address newOwner) external override onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } /// @dev Only the owner may upgrade the contract, the pauseGuardian may downgrade the contract /// to a predetermined router contract that provides read only access to the system. function _authorizeUpgrade(address newImplementation) internal override { require( owner == msg.sender || (msg.sender == pauseGuardian && newImplementation == pauseRouter), "Unauthorized upgrade" ); // This is set temporarily during a downgrade to the pauseRouter so that the upgrade // will pass _authorizeUpgrade on the pauseRouter during the UUPSUpgradeable rollback check if (newImplementation == pauseRouter) rollbackRouterImplementation = _getImplementation(); } /// @notice Sets a new pause router and guardian address. function setPauseRouterAndGuardian( address pauseRouter_, address pauseGuardian_ ) external override onlyOwner { pauseRouter = pauseRouter_; pauseGuardian = pauseGuardian_; emit PauseRouterAndGuardianUpdated(pauseRouter_, pauseGuardian_); } /// @notice Lists a new currency along with its exchange rate to ETH /// @dev emit:ListCurrency emit:UpdateETHRate /// @param assetToken the token parameters for the asset token /// @param underlyingToken the underlying token (if asset token is an interest bearing wrapper) /// @param rateOracle ETH to underlying rate oracle /// @param mustInvert if the rate from the oracle needs to be inverted /// @param buffer multiplier (>= 100) for negative balances when calculating free collateral /// @param haircut multiplier (<= 100) for positive balances when calculating free collateral /// @param liquidationDiscount multiplier (>= 100) for exchange rate when liquidating /// @return the new currency id function listCurrency( TokenStorage calldata assetToken, TokenStorage calldata underlyingToken, AggregatorV2V3Interface rateOracle, bool mustInvert, uint8 buffer, uint8 haircut, uint8 liquidationDiscount ) external override onlyOwner returns (uint16) { uint16 currencyId = maxCurrencyId + 1; // Set the new max currency id maxCurrencyId = currencyId; require(currencyId <= Constants.MAX_CURRENCIES, "G: max currency overflow"); // NOTE: this allows multiple asset tokens that have the same underlying. That is ok from a protocol // perspective. For example, we may choose list cDAI, yDAI and aDAI as asset currencies and each can // trade as different forms of fDAI. require( tokenAddressToCurrencyId[assetToken.tokenAddress] == 0, "G: duplicate token listing" ); tokenAddressToCurrencyId[assetToken.tokenAddress] = currencyId; // Set the underlying first because the asset token may set an approval using the underlying if ( underlyingToken.tokenAddress != address(0) || // Ether has a token address of zero underlyingToken.tokenType == TokenType.Ether ) { // NOTE: set token will enforce the restriction that Ether can only be set once as the zero // address. This sets the underlying token TokenHandler.setToken(currencyId, true, underlyingToken); } // This sets the asset token TokenHandler.setToken(currencyId, false, assetToken); _updateETHRate(currencyId, rateOracle, mustInvert, buffer, haircut, liquidationDiscount); emit ListCurrency(currencyId); return currencyId; } /// @notice Sets a maximum balance on a given currency. Max collateral balance cannot be set on a /// currency that is actively used in trading, this may cause issues with liquidation. Also, max /// collateral balance is only set on asset tokens (not underlying tokens) because underlying tokens /// are not held as contract balances. /// @dev emit:UpdateMaxCollateralBalance /// @param currencyId id of the currency to set the max collateral balance on /// @param maxCollateralBalanceInternalPrecision amount of collateral balance that can be held /// in this currency denominated in internal token precision function updateMaxCollateralBalance( uint16 currencyId, uint72 maxCollateralBalanceInternalPrecision ) external override onlyOwner { _checkValidCurrency(currencyId); // Cannot turn on max collateral balance for a currency that is trading if (maxCollateralBalanceInternalPrecision > 0) require(CashGroup.getMaxMarketIndex(currencyId) == 0); TokenHandler.setMaxCollateralBalance(currencyId, maxCollateralBalanceInternalPrecision); emit UpdateMaxCollateralBalance(currencyId, maxCollateralBalanceInternalPrecision); } /// @notice Enables a cash group on a given currency so that it can have lend and borrow markets. Will /// also deploy an nToken contract so that markets can be initialized. /// @dev emit:UpdateCashGroup emit:UpdateAssetRate emit:DeployNToken /// @param currencyId id of the currency to enable /// @param assetRateOracle address of the rate oracle for converting interest bearing assets to /// underlying values /// @param cashGroup parameters for the cash group /// @param underlyingName underlying token name for seeding nToken name /// @param underlyingSymbol underlying token symbol for seeding nToken symbol (i.e. nDAI) function enableCashGroup( uint16 currencyId, AssetRateAdapter assetRateOracle, CashGroupSettings calldata cashGroup, string calldata underlyingName, string calldata underlyingSymbol ) external override onlyOwner { _checkValidCurrency(currencyId); { // Cannot enable fCash trading on a token with a max collateral balance Token memory assetToken = TokenHandler.getAssetToken(currencyId); Token memory underlyingToken = TokenHandler.getUnderlyingToken(currencyId); require( assetToken.maxCollateralBalance == 0 && underlyingToken.maxCollateralBalance == 0 ); // dev: cannot enable trading, collateral cap } _updateCashGroup(currencyId, cashGroup); _updateAssetRate(currencyId, assetRateOracle); // Creates the nToken erc20 proxy that routes back to the main contract nTokenERC20Proxy proxy = new nTokenERC20Proxy( nTokenERC20(address(this)), currencyId, underlyingName, underlyingSymbol ); nTokenHandler.setNTokenAddress(currencyId, address(proxy)); emit DeployNToken(currencyId, address(proxy)); } /// @notice Updates the deposit parameters for an nToken /// @dev emit:UpdateDepositParameters /// @param currencyId the currency id that the nToken references /// @param depositShares an array of values that represent the proportion of each deposit /// that will go to a respective market, must add up to DEPOSIT_PERCENT_BASIS. For example, /// 0.40e8, 0.40e8 and 0.20e8 will result in 40%, 40% and 20% deposited as liquidity into /// the 3 month, 6 month and 1 year markets. /// @param leverageThresholds an array of values denominated in RATE_PRECISION that mark the /// highest proportion of fCash where the nToken will provide liquidity. Above this proportion, /// the nToken will lend to the market instead to reduce the leverage in the market. function updateDepositParameters( uint16 currencyId, uint32[] calldata depositShares, uint32[] calldata leverageThresholds ) external override onlyOwner { _checkValidCurrency(currencyId); nTokenHandler.setDepositParameters(currencyId, depositShares, leverageThresholds); emit UpdateDepositParameters(currencyId); } /// @notice Updates the market initialization parameters for an nToken /// @dev emit:UpdateInitializationParameters /// @param currencyId the currency id that the nToken references /// @param annualizedAnchorRates is a target interest rate that will be used to calculate a /// rate anchor during initialize markets. This rate anchor will set the offset from the /// x-axis where the liquidity curve will be initialized. This is used in combination with /// previous market rates to determine the initial proportion where markets will be initialized /// every quarter. /// @param proportions used to combination with annualizedAnchorRate set the initial proportion when /// a market is first initialized. This is required since there is no previous rate to reference. function updateInitializationParameters( uint16 currencyId, uint32[] calldata annualizedAnchorRates, uint32[] calldata proportions ) external override onlyOwner { _checkValidCurrency(currencyId); nTokenHandler.setInitializationParameters(currencyId, annualizedAnchorRates, proportions); emit UpdateInitializationParameters(currencyId); } /// @notice Updates the emission rate of incentives for a given currency /// @dev emit:UpdateIncentiveEmissionRate /// @param currencyId the currency id that the nToken references /// @param newEmissionRate Target total incentives to emit for an nToken over an entire year /// denominated in WHOLE TOKENS (i.e. setting this to 1 means 1e8 tokens). The rate will not be /// exact due to multiplier effects and fluctuating token supply. function updateIncentiveEmissionRate(uint16 currencyId, uint32 newEmissionRate) external override onlyOwner { _checkValidCurrency(currencyId); address nTokenAddress = nTokenHandler.nTokenAddress(currencyId); require(nTokenAddress != address(0), "Invalid currency"); // Sanity check that emissions rate is not specified in 1e8 terms. require(newEmissionRate < Constants.INTERNAL_TOKEN_PRECISION, "Invalid rate"); nTokenHandler.setIncentiveEmissionRate(nTokenAddress, newEmissionRate); emit UpdateIncentiveEmissionRate(currencyId, newEmissionRate); } /// @notice Updates collateralization parameters for an nToken /// @dev emit:UpdateTokenCollateralParameters /// @param currencyId the currency id that the nToken references /// @param residualPurchaseIncentive10BPS nTokens will have residual amounts of fCash at the end of each /// quarter that are "dead weight" because they are at idiosyncratic maturities and do not contribute to /// actively providing liquidity. This parameter will incentivize market participants to purchase these residuals /// at a discount from the on chain oracle rate, denominated in 10 basis point increments. These residuals will /// be added back into nToken balances and will be used to provide liquidity upon the next market initialization. /// @param pvHaircutPercentage a percentage (< 100) that the present value of the nToken's assets will be valued /// at for the purposes of free collateral, relevant when accounts hold nTokens as collateral against debts. /// @param residualPurchaseTimeBufferHours an arbitrage opportunity is available by pushing markets in one direction /// before quarterly settlement to generate large residual balances that can be purchased at a discount. The time buffer /// here ensures that anyone attempting such an act would have to wait some number of hours (likely a few days) before /// they could attempt to purchase residuals, ensuring that the market could realign to rates where the arbitrage is /// no longer possible. /// @param cashWithholdingBuffer10BPS nToken residuals may be negative fCash (debt), in this case cash is withheld to /// transfer to accounts that take on the debt. This parameter denominates the discounted rate at which the cash will /// be withheld at for this purpose. /// @param liquidationHaircutPercentage a percentage of nToken present value (> pvHaircutPercentage and <= 100) at which /// liquidators will purchase nTokens during liquidation function updateTokenCollateralParameters( uint16 currencyId, uint8 residualPurchaseIncentive10BPS, uint8 pvHaircutPercentage, uint8 residualPurchaseTimeBufferHours, uint8 cashWithholdingBuffer10BPS, uint8 liquidationHaircutPercentage ) external override onlyOwner { _checkValidCurrency(currencyId); address nTokenAddress = nTokenHandler.nTokenAddress(currencyId); require(nTokenAddress != address(0), "Invalid currency"); nTokenHandler.setNTokenCollateralParameters( nTokenAddress, residualPurchaseIncentive10BPS, pvHaircutPercentage, residualPurchaseTimeBufferHours, cashWithholdingBuffer10BPS, liquidationHaircutPercentage ); emit UpdateTokenCollateralParameters(currencyId); } /// @notice Updates cash group parameters /// @dev emit:UpdateCashGroup /// @param currencyId id of the currency to enable /// @param cashGroup new parameters for the cash group function updateCashGroup(uint16 currencyId, CashGroupSettings calldata cashGroup) external override onlyOwner { _checkValidCurrency(currencyId); _updateCashGroup(currencyId, cashGroup); } /// @notice Updates asset rate oracle /// @dev emit:UpdateAssetRate /// @param currencyId id of the currency /// @param rateOracle new rate oracle for the asset function updateAssetRate(uint16 currencyId, AssetRateAdapter rateOracle) external override onlyOwner { _checkValidCurrency(currencyId); _updateAssetRate(currencyId, rateOracle); } /// @notice Updates ETH exchange rate or related parameters /// @dev emit:UpdateETHRate /// @param currencyId id of the currency /// @param rateOracle new rate oracle for the asset /// @param rateOracle ETH to underlying rate oracle /// @param mustInvert if the rate from the oracle needs to be inverted /// @param buffer multiplier (>= 100) for negative balances when calculating free collateral /// @param haircut multiplier (<= 100) for positive balances when calculating free collateral /// @param liquidationDiscount multiplier (>= 100) for exchange rate when liquidating function updateETHRate( uint16 currencyId, AggregatorV2V3Interface rateOracle, bool mustInvert, uint8 buffer, uint8 haircut, uint8 liquidationDiscount ) external override onlyOwner { _checkValidCurrency(currencyId); _updateETHRate(currencyId, rateOracle, mustInvert, buffer, haircut, liquidationDiscount); } /// @notice Sets a global transfer operator that can do authenticated ERC1155 transfers. This enables /// OTC trading or other use cases such as layer 2 authenticated transfers. /// @dev emit:UpdateGlobalTransferOperator /// @param operator address of the operator /// @param approved true if the operator is allowed to transfer globally function updateGlobalTransferOperator(address operator, bool approved) external override onlyOwner { // Sanity check to ensure that operator is a contract, not an EOA require(Address.isContract(operator), "Operator must be a contract"); globalTransferOperator[operator] = approved; emit UpdateGlobalTransferOperator(operator, approved); } /// @notice Approves contracts that can call `batchTradeActionWithCallback`. These contracts can /// "flash loan" from Notional V2 and receive a callback before the free collateral check. Flash loans /// via the Notional V2 liquidity pool are not very gas efficient so this is not generally available, /// it can be used for migrating borrows into Notional V2 from other platforms. /// @dev emit:UpdateAuthorizedCallbackContract /// @param operator address of the contract /// @param approved true if the contract is authorized function updateAuthorizedCallbackContract(address operator, bool approved) external override onlyOwner { // Sanity check to ensure that operator is a contract, not an EOA require(Address.isContract(operator), "Operator must be a contract"); authorizedCallbackContract[operator] = approved; emit UpdateAuthorizedCallbackContract(operator, approved); } function _updateCashGroup(uint16 currencyId, CashGroupSettings calldata cashGroup) internal { CashGroup.setCashGroupStorage(currencyId, cashGroup); emit UpdateCashGroup(currencyId); } function _updateAssetRate(uint16 currencyId, AssetRateAdapter rateOracle) internal { // If rate oracle refers to address zero then do not apply any updates here, this means // that a token is non mintable. Token memory assetToken = TokenHandler.getAssetToken(currencyId); if (address(rateOracle) == address(0)) { // Sanity check that unset rate oracles are only for non mintable tokens require(assetToken.tokenType == TokenType.NonMintable, "G: invalid asset rate"); } else { // Sanity check that the rate oracle refers to the proper asset token address token = AssetRateAdapter(rateOracle).token(); require(assetToken.tokenAddress == token, "G: invalid rate oracle"); uint8 underlyingDecimals; if (currencyId == Constants.ETH_CURRENCY_ID) { // If currencyId is one then this is referring to cETH and there is no underlying() to call underlyingDecimals = Constants.ETH_DECIMAL_PLACES; } else { address underlyingTokenAddress = AssetRateAdapter(rateOracle).underlying(); Token memory underlyingToken = TokenHandler.getUnderlyingToken(currencyId); // Sanity check to ensure that the asset rate adapter refers to the correct underlying require(underlyingTokenAddress == underlyingToken.tokenAddress, "G: invalid adapter"); underlyingDecimals = ERC20(underlyingTokenAddress).decimals(); } // Perform this check to ensure that decimal calculations don't overflow require(underlyingDecimals <= Constants.MAX_DECIMAL_PLACES); mapping(uint256 => AssetRateStorage) storage store = LibStorage.getAssetRateStorage(); store[currencyId] = AssetRateStorage({ rateOracle: rateOracle, underlyingDecimalPlaces: underlyingDecimals }); emit UpdateAssetRate(currencyId); } } function _updateETHRate( uint16 currencyId, AggregatorV2V3Interface rateOracle, bool mustInvert, uint8 buffer, uint8 haircut, uint8 liquidationDiscount ) internal { uint8 rateDecimalPlaces; if (currencyId == Constants.ETH_CURRENCY_ID) { // ETH to ETH exchange rate is fixed at 1 and has no rate oracle rateOracle = AggregatorV2V3Interface(address(0)); rateDecimalPlaces = Constants.ETH_DECIMAL_PLACES; } else { require(address(rateOracle) != address(0), "G: zero rate oracle address"); rateDecimalPlaces = rateOracle.decimals(); } require(buffer >= Constants.PERCENTAGE_DECIMALS, "G: buffer must be gte decimals"); require(haircut <= Constants.PERCENTAGE_DECIMALS, "G: buffer must be lte decimals"); require( liquidationDiscount > Constants.PERCENTAGE_DECIMALS, "G: discount must be gt decimals" ); // Perform this check to ensure that decimal calculations don't overflow require(rateDecimalPlaces <= Constants.MAX_DECIMAL_PLACES); mapping(uint256 => ETHRateStorage) storage store = LibStorage.getExchangeRateStorage(); store[currencyId] = ETHRateStorage({ rateOracle: rateOracle, rateDecimalPlaces: rateDecimalPlaces, mustInvert: mustInvert, buffer: buffer, haircut: haircut, liquidationDiscount: liquidationDiscount }); emit UpdateETHRate(currencyId); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../balances/TokenHandler.sol"; import "../../math/SafeInt256.sol"; import "interfaces/chainlink/AggregatorV2V3Interface.sol"; library ExchangeRate { using SafeInt256 for int256; /// @notice Converts a balance to ETH from a base currency. Buffers or haircuts are /// always applied in this method. /// @param er exchange rate object from base to ETH /// @return the converted balance denominated in ETH with Constants.INTERNAL_TOKEN_PRECISION function convertToETH(ETHRate memory er, int256 balance) internal pure returns (int256) { int256 multiplier = balance > 0 ? er.haircut : er.buffer; // We are converting internal balances here so we know they have INTERNAL_TOKEN_PRECISION decimals // internalDecimals * rateDecimals * multiplier / (rateDecimals * multiplierDecimals) // Therefore the result is in ethDecimals int256 result = balance.mul(er.rate).mul(multiplier).div(Constants.PERCENTAGE_DECIMALS).div( er.rateDecimals ); return result; } /// @notice Converts the balance denominated in ETH to the equivalent value in a base currency. /// Buffers and haircuts ARE NOT applied in this method. /// @param er exchange rate object from base to ETH /// @param balance amount (denominated in ETH) to convert function convertETHTo(ETHRate memory er, int256 balance) internal pure returns (int256) { // We are converting internal balances here so we know they have INTERNAL_TOKEN_PRECISION decimals // internalDecimals * rateDecimals / rateDecimals int256 result = balance.mul(er.rateDecimals).div(er.rate); return result; } /// @notice Calculates the exchange rate between two currencies via ETH. Returns the rate denominated in /// base exchange rate decimals: (baseRateDecimals * quoteRateDecimals) / quoteRateDecimals /// @param baseER base exchange rate struct /// @param quoteER quote exchange rate struct function exchangeRate(ETHRate memory baseER, ETHRate memory quoteER) internal pure returns (int256) { return baseER.rate.mul(quoteER.rateDecimals).div(quoteER.rate); } /// @notice Returns an ETHRate object used to calculate free collateral function buildExchangeRate(uint256 currencyId) internal view returns (ETHRate memory) { mapping(uint256 => ETHRateStorage) storage store = LibStorage.getExchangeRateStorage(); ETHRateStorage storage ethStorage = store[currencyId]; int256 rateDecimals; int256 rate; if (currencyId == Constants.ETH_CURRENCY_ID) { // ETH rates will just be 1e18, but will still have buffers, haircuts, // and liquidation discounts rateDecimals = Constants.ETH_DECIMALS; rate = Constants.ETH_DECIMALS; } else { // prettier-ignore ( /* roundId */, rate, /* uint256 startedAt */, /* updatedAt */, /* answeredInRound */ ) = ethStorage.rateOracle.latestRoundData(); require(rate > 0, "Invalid rate"); // No overflow, restricted on storage rateDecimals = int256(10**ethStorage.rateDecimalPlaces); if (ethStorage.mustInvert) { rate = rateDecimals.mul(rateDecimals).div(rate); } } return ETHRate({ rateDecimals: rateDecimals, rate: rate, buffer: ethStorage.buffer, haircut: ethStorage.haircut, liquidationDiscount: ethStorage.liquidationDiscount }); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "./Market.sol"; import "./AssetRate.sol"; import "./DateTime.sol"; import "../../global/LibStorage.sol"; import "../../global/Types.sol"; import "../../global/Constants.sol"; import "../../math/SafeInt256.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; library CashGroup { using SafeMath for uint256; using SafeInt256 for int256; using AssetRate for AssetRateParameters; using Market for MarketParameters; // Bit number references for each parameter in the 32 byte word (0-indexed) uint256 private constant MARKET_INDEX_BIT = 31; uint256 private constant RATE_ORACLE_TIME_WINDOW_BIT = 30; uint256 private constant TOTAL_FEE_BIT = 29; uint256 private constant RESERVE_FEE_SHARE_BIT = 28; uint256 private constant DEBT_BUFFER_BIT = 27; uint256 private constant FCASH_HAIRCUT_BIT = 26; uint256 private constant SETTLEMENT_PENALTY_BIT = 25; uint256 private constant LIQUIDATION_FCASH_HAIRCUT_BIT = 24; uint256 private constant LIQUIDATION_DEBT_BUFFER_BIT = 23; // 7 bytes allocated, one byte per market for the liquidity token haircut uint256 private constant LIQUIDITY_TOKEN_HAIRCUT_FIRST_BIT = 22; // 7 bytes allocated, one byte per market for the rate scalar uint256 private constant RATE_SCALAR_FIRST_BIT = 15; // Offsets for the bytes of the different parameters uint256 private constant MARKET_INDEX = (31 - MARKET_INDEX_BIT) * 8; uint256 private constant RATE_ORACLE_TIME_WINDOW = (31 - RATE_ORACLE_TIME_WINDOW_BIT) * 8; uint256 private constant TOTAL_FEE = (31 - TOTAL_FEE_BIT) * 8; uint256 private constant RESERVE_FEE_SHARE = (31 - RESERVE_FEE_SHARE_BIT) * 8; uint256 private constant DEBT_BUFFER = (31 - DEBT_BUFFER_BIT) * 8; uint256 private constant FCASH_HAIRCUT = (31 - FCASH_HAIRCUT_BIT) * 8; uint256 private constant SETTLEMENT_PENALTY = (31 - SETTLEMENT_PENALTY_BIT) * 8; uint256 private constant LIQUIDATION_FCASH_HAIRCUT = (31 - LIQUIDATION_FCASH_HAIRCUT_BIT) * 8; uint256 private constant LIQUIDATION_DEBT_BUFFER = (31 - LIQUIDATION_DEBT_BUFFER_BIT) * 8; uint256 private constant LIQUIDITY_TOKEN_HAIRCUT = (31 - LIQUIDITY_TOKEN_HAIRCUT_FIRST_BIT) * 8; uint256 private constant RATE_SCALAR = (31 - RATE_SCALAR_FIRST_BIT) * 8; /// @notice Returns the rate scalar scaled by time to maturity. The rate scalar multiplies /// the ln() portion of the liquidity curve as an inverse so it increases with time to /// maturity. The effect of the rate scalar on slippage must decrease with time to maturity. function getRateScalar( CashGroupParameters memory cashGroup, uint256 marketIndex, uint256 timeToMaturity ) internal pure returns (int256) { require(1 <= marketIndex && marketIndex <= cashGroup.maxMarketIndex); // dev: invalid market index uint256 offset = RATE_SCALAR + 8 * (marketIndex - 1); int256 scalar = int256(uint8(uint256(cashGroup.data >> offset))) * Constants.RATE_PRECISION; int256 rateScalar = scalar.mul(int256(Constants.IMPLIED_RATE_TIME)).div(SafeInt256.toInt(timeToMaturity)); // Rate scalar is denominated in RATE_PRECISION, it is unlikely to underflow in the // division above. require(rateScalar > 0); // dev: rate scalar underflow return rateScalar; } /// @notice Haircut on liquidity tokens to account for the risk associated with changes in the /// proportion of cash to fCash within the pool. This is set as a percentage less than or equal to 100. function getLiquidityHaircut(CashGroupParameters memory cashGroup, uint256 assetType) internal pure returns (uint8) { require( Constants.MIN_LIQUIDITY_TOKEN_INDEX <= assetType && assetType <= Constants.MAX_LIQUIDITY_TOKEN_INDEX ); // dev: liquidity haircut invalid asset type uint256 offset = LIQUIDITY_TOKEN_HAIRCUT + 8 * (assetType - Constants.MIN_LIQUIDITY_TOKEN_INDEX); return uint8(uint256(cashGroup.data >> offset)); } /// @notice Total trading fee denominated in RATE_PRECISION with basis point increments function getTotalFee(CashGroupParameters memory cashGroup) internal pure returns (uint256) { return uint256(uint8(uint256(cashGroup.data >> TOTAL_FEE))) * Constants.BASIS_POINT; } /// @notice Percentage of the total trading fee that goes to the reserve function getReserveFeeShare(CashGroupParameters memory cashGroup) internal pure returns (int256) { return uint8(uint256(cashGroup.data >> RESERVE_FEE_SHARE)); } /// @notice fCash haircut for valuation denominated in rate precision with five basis point increments function getfCashHaircut(CashGroupParameters memory cashGroup) internal pure returns (uint256) { return uint256(uint8(uint256(cashGroup.data >> FCASH_HAIRCUT))) * Constants.FIVE_BASIS_POINTS; } /// @notice fCash debt buffer for valuation denominated in rate precision with five basis point increments function getDebtBuffer(CashGroupParameters memory cashGroup) internal pure returns (uint256) { return uint256(uint8(uint256(cashGroup.data >> DEBT_BUFFER))) * Constants.FIVE_BASIS_POINTS; } /// @notice Time window factor for the rate oracle denominated in seconds with five minute increments. function getRateOracleTimeWindow(CashGroupParameters memory cashGroup) internal pure returns (uint256) { // This is denominated in 5 minute increments in storage return uint256(uint8(uint256(cashGroup.data >> RATE_ORACLE_TIME_WINDOW))) * Constants.FIVE_MINUTES; } /// @notice Penalty rate for settling cash debts denominated in basis points function getSettlementPenalty(CashGroupParameters memory cashGroup) internal pure returns (uint256) { return uint256(uint8(uint256(cashGroup.data >> SETTLEMENT_PENALTY))) * Constants.FIVE_BASIS_POINTS; } /// @notice Haircut for positive fCash during liquidation denominated rate precision /// with five basis point increments function getLiquidationfCashHaircut(CashGroupParameters memory cashGroup) internal pure returns (uint256) { return uint256(uint8(uint256(cashGroup.data >> LIQUIDATION_FCASH_HAIRCUT))) * Constants.FIVE_BASIS_POINTS; } /// @notice Haircut for negative fCash during liquidation denominated rate precision /// with five basis point increments function getLiquidationDebtBuffer(CashGroupParameters memory cashGroup) internal pure returns (uint256) { return uint256(uint8(uint256(cashGroup.data >> LIQUIDATION_DEBT_BUFFER))) * Constants.FIVE_BASIS_POINTS; } function loadMarket( CashGroupParameters memory cashGroup, MarketParameters memory market, uint256 marketIndex, bool needsLiquidity, uint256 blockTime ) internal view { require(1 <= marketIndex && marketIndex <= cashGroup.maxMarketIndex, "Invalid market"); uint256 maturity = DateTime.getReferenceTime(blockTime).add(DateTime.getTradedMarket(marketIndex)); market.loadMarket( cashGroup.currencyId, maturity, blockTime, needsLiquidity, getRateOracleTimeWindow(cashGroup) ); } /// @notice Returns the linear interpolation between two market rates. The formula is /// slope = (longMarket.oracleRate - shortMarket.oracleRate) / (longMarket.maturity - shortMarket.maturity) /// interpolatedRate = slope * (assetMaturity - shortMarket.maturity) + shortMarket.oracleRate function interpolateOracleRate( uint256 shortMaturity, uint256 longMaturity, uint256 shortRate, uint256 longRate, uint256 assetMaturity ) internal pure returns (uint256) { require(shortMaturity < assetMaturity); // dev: cash group interpolation error, short maturity require(assetMaturity < longMaturity); // dev: cash group interpolation error, long maturity // It's possible that the rates are inverted where the short market rate > long market rate and // we will get an underflow here so we check for that if (longRate >= shortRate) { return (longRate - shortRate) .mul(assetMaturity - shortMaturity) // No underflow here, checked above .div(longMaturity - shortMaturity) .add(shortRate); } else { // In this case the slope is negative so: // interpolatedRate = shortMarket.oracleRate - slope * (assetMaturity - shortMarket.maturity) // NOTE: this subtraction should never overflow, the linear interpolation between two points above zero // cannot go below zero return shortRate.sub( // This is reversed to keep it it positive (shortRate - longRate) .mul(assetMaturity - shortMaturity) // No underflow here, checked above .div(longMaturity - shortMaturity) ); } } /// @dev Gets an oracle rate given any valid maturity. function calculateOracleRate( CashGroupParameters memory cashGroup, uint256 maturity, uint256 blockTime ) internal view returns (uint256) { (uint256 marketIndex, bool idiosyncratic) = DateTime.getMarketIndex(cashGroup.maxMarketIndex, maturity, blockTime); uint256 timeWindow = getRateOracleTimeWindow(cashGroup); if (!idiosyncratic) { return Market.getOracleRate(cashGroup.currencyId, maturity, timeWindow, blockTime); } else { uint256 referenceTime = DateTime.getReferenceTime(blockTime); // DateTime.getMarketIndex returns the market that is past the maturity if idiosyncratic uint256 longMaturity = referenceTime.add(DateTime.getTradedMarket(marketIndex)); uint256 longRate = Market.getOracleRate(cashGroup.currencyId, longMaturity, timeWindow, blockTime); uint256 shortMaturity; uint256 shortRate; if (marketIndex == 1) { // In this case the short market is the annualized asset supply rate shortMaturity = blockTime; shortRate = cashGroup.assetRate.getSupplyRate(); } else { // Minimum value for marketIndex here is 2 shortMaturity = referenceTime.add(DateTime.getTradedMarket(marketIndex - 1)); shortRate = Market.getOracleRate( cashGroup.currencyId, shortMaturity, timeWindow, blockTime ); } return interpolateOracleRate(shortMaturity, longMaturity, shortRate, longRate, maturity); } } function _getCashGroupStorageBytes(uint256 currencyId) private view returns (bytes32 data) { mapping(uint256 => bytes32) storage store = LibStorage.getCashGroupStorage(); return store[currencyId]; } /// @dev Helper method for validating maturities in ERC1155Action function getMaxMarketIndex(uint256 currencyId) internal view returns (uint8) { bytes32 data = _getCashGroupStorageBytes(currencyId); return uint8(data[MARKET_INDEX_BIT]); } /// @notice Checks all cash group settings for invalid values and sets them into storage function setCashGroupStorage(uint256 currencyId, CashGroupSettings calldata cashGroup) internal { // Due to the requirements of the yield curve we do not allow a cash group to have solely a 3 month market. // The reason is that borrowers will not have a further maturity to roll from their 3 month fixed to a 6 month // fixed. It also complicates the logic in the nToken initialization method. Additionally, we cannot have cash // groups with 0 market index, it has no effect. require(2 <= cashGroup.maxMarketIndex && cashGroup.maxMarketIndex <= Constants.MAX_TRADED_MARKET_INDEX, "CG: invalid market index" ); require( cashGroup.reserveFeeShare <= Constants.PERCENTAGE_DECIMALS, "CG: invalid reserve share" ); require(cashGroup.liquidityTokenHaircuts.length == cashGroup.maxMarketIndex); require(cashGroup.rateScalars.length == cashGroup.maxMarketIndex); // This is required so that fCash liquidation can proceed correctly require(cashGroup.liquidationfCashHaircut5BPS < cashGroup.fCashHaircut5BPS); require(cashGroup.liquidationDebtBuffer5BPS < cashGroup.debtBuffer5BPS); // Market indexes cannot decrease or they will leave fCash assets stranded in the future with no valuation curve uint8 previousMaxMarketIndex = getMaxMarketIndex(currencyId); require( previousMaxMarketIndex <= cashGroup.maxMarketIndex, "CG: market index cannot decrease" ); // Per cash group settings bytes32 data = (bytes32(uint256(cashGroup.maxMarketIndex)) | (bytes32(uint256(cashGroup.rateOracleTimeWindow5Min)) << RATE_ORACLE_TIME_WINDOW) | (bytes32(uint256(cashGroup.totalFeeBPS)) << TOTAL_FEE) | (bytes32(uint256(cashGroup.reserveFeeShare)) << RESERVE_FEE_SHARE) | (bytes32(uint256(cashGroup.debtBuffer5BPS)) << DEBT_BUFFER) | (bytes32(uint256(cashGroup.fCashHaircut5BPS)) << FCASH_HAIRCUT) | (bytes32(uint256(cashGroup.settlementPenaltyRate5BPS)) << SETTLEMENT_PENALTY) | (bytes32(uint256(cashGroup.liquidationfCashHaircut5BPS)) << LIQUIDATION_FCASH_HAIRCUT) | (bytes32(uint256(cashGroup.liquidationDebtBuffer5BPS)) << LIQUIDATION_DEBT_BUFFER)); // Per market group settings for (uint256 i = 0; i < cashGroup.liquidityTokenHaircuts.length; i++) { require( cashGroup.liquidityTokenHaircuts[i] <= Constants.PERCENTAGE_DECIMALS, "CG: invalid token haircut" ); data = data | (bytes32(uint256(cashGroup.liquidityTokenHaircuts[i])) << (LIQUIDITY_TOKEN_HAIRCUT + i * 8)); } for (uint256 i = 0; i < cashGroup.rateScalars.length; i++) { // Causes a divide by zero error require(cashGroup.rateScalars[i] != 0, "CG: invalid rate scalar"); data = data | (bytes32(uint256(cashGroup.rateScalars[i])) << (RATE_SCALAR + i * 8)); } mapping(uint256 => bytes32) storage store = LibStorage.getCashGroupStorage(); store[currencyId] = data; } /// @notice Deserialize the cash group storage bytes into a user friendly object function deserializeCashGroupStorage(uint256 currencyId) internal view returns (CashGroupSettings memory) { bytes32 data = _getCashGroupStorageBytes(currencyId); uint8 maxMarketIndex = uint8(data[MARKET_INDEX_BIT]); uint8[] memory tokenHaircuts = new uint8[](uint256(maxMarketIndex)); uint8[] memory rateScalars = new uint8[](uint256(maxMarketIndex)); for (uint8 i = 0; i < maxMarketIndex; i++) { tokenHaircuts[i] = uint8(data[LIQUIDITY_TOKEN_HAIRCUT_FIRST_BIT - i]); rateScalars[i] = uint8(data[RATE_SCALAR_FIRST_BIT - i]); } return CashGroupSettings({ maxMarketIndex: maxMarketIndex, rateOracleTimeWindow5Min: uint8(data[RATE_ORACLE_TIME_WINDOW_BIT]), totalFeeBPS: uint8(data[TOTAL_FEE_BIT]), reserveFeeShare: uint8(data[RESERVE_FEE_SHARE_BIT]), debtBuffer5BPS: uint8(data[DEBT_BUFFER_BIT]), fCashHaircut5BPS: uint8(data[FCASH_HAIRCUT_BIT]), settlementPenaltyRate5BPS: uint8(data[SETTLEMENT_PENALTY_BIT]), liquidationfCashHaircut5BPS: uint8(data[LIQUIDATION_FCASH_HAIRCUT_BIT]), liquidationDebtBuffer5BPS: uint8(data[LIQUIDATION_DEBT_BUFFER_BIT]), liquidityTokenHaircuts: tokenHaircuts, rateScalars: rateScalars }); } function _buildCashGroup(uint16 currencyId, AssetRateParameters memory assetRate) private view returns (CashGroupParameters memory) { bytes32 data = _getCashGroupStorageBytes(currencyId); uint256 maxMarketIndex = uint8(data[MARKET_INDEX_BIT]); return CashGroupParameters({ currencyId: currencyId, maxMarketIndex: maxMarketIndex, assetRate: assetRate, data: data }); } /// @notice Builds a cash group using a view version of the asset rate function buildCashGroupView(uint16 currencyId) internal view returns (CashGroupParameters memory) { AssetRateParameters memory assetRate = AssetRate.buildAssetRateView(currencyId); return _buildCashGroup(currencyId, assetRate); } /// @notice Builds a cash group using a stateful version of the asset rate function buildCashGroupStateful(uint16 currencyId) internal returns (CashGroupParameters memory) { AssetRateParameters memory assetRate = AssetRate.buildAssetRateStateful(currencyId); return _buildCashGroup(currencyId, assetRate); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../global/LibStorage.sol"; import "./markets/CashGroup.sol"; import "./markets/AssetRate.sol"; import "./valuation/AssetHandler.sol"; import "./portfolio/BitmapAssetsHandler.sol"; import "./portfolio/PortfolioHandler.sol"; import "./balances/BalanceHandler.sol"; import "../math/SafeInt256.sol"; library nTokenHandler { using AssetRate for AssetRateParameters; using SafeInt256 for int256; /// @dev Mirror of the value in LibStorage uint256 private constant NUM_NTOKEN_MARKET_FACTORS = 14; /// @notice Returns an account context object that is specific to nTokens. function getNTokenContext(address tokenAddress) internal view returns ( uint16 currencyId, uint256 incentiveAnnualEmissionRate, uint256 lastInitializedTime, uint8 assetArrayLength, bytes5 parameters ) { mapping(address => nTokenContext) storage store = LibStorage.getNTokenContextStorage(); nTokenContext storage context = store[tokenAddress]; // TODO: how many storage reads is this? currencyId = context.currencyId; incentiveAnnualEmissionRate = context.incentiveAnnualEmissionRate; lastInitializedTime = context.lastInitializedTime; assetArrayLength = context.assetArrayLength; parameters = context.nTokenParameters; } /// @notice Returns the nToken token address for a given currency function nTokenAddress(uint256 currencyId) internal view returns (address tokenAddress) { mapping(uint256 => address) storage store = LibStorage.getNTokenAddressStorage(); return store[currencyId]; } /// @notice Called by governance to set the nToken token address and its reverse lookup. Cannot be /// reset once this is set. function setNTokenAddress(uint16 currencyId, address tokenAddress) internal { mapping(uint256 => address) storage addressStore = LibStorage.getNTokenAddressStorage(); require(addressStore[currencyId] == address(0), "PT: token address exists"); mapping(address => nTokenContext) storage contextStore = LibStorage.getNTokenContextStorage(); nTokenContext storage context = contextStore[tokenAddress]; require(context.currencyId == 0, "PT: currency exists"); // This will initialize all other context slots to zero context.currencyId = currencyId; addressStore[currencyId] = tokenAddress; } /// @notice Set nToken token collateral parameters function setNTokenCollateralParameters( address tokenAddress, uint8 residualPurchaseIncentive10BPS, uint8 pvHaircutPercentage, uint8 residualPurchaseTimeBufferHours, uint8 cashWithholdingBuffer10BPS, uint8 liquidationHaircutPercentage ) internal { mapping(address => nTokenContext) storage store = LibStorage.getNTokenContextStorage(); nTokenContext storage context = store[tokenAddress]; require(liquidationHaircutPercentage <= Constants.PERCENTAGE_DECIMALS, "Invalid haircut"); // The pv haircut percentage must be less than the liquidation percentage or else liquidators will not // get profit for liquidating nToken. require(pvHaircutPercentage < liquidationHaircutPercentage, "Invalid pv haircut"); // Ensure that the cash withholding buffer is greater than the residual purchase incentive or // the nToken may not have enough cash to pay accounts to buy its negative ifCash require(residualPurchaseIncentive10BPS <= cashWithholdingBuffer10BPS, "Invalid discounts"); bytes5 parameters = (bytes5(uint40(residualPurchaseIncentive10BPS)) | (bytes5(uint40(pvHaircutPercentage)) << 8) | (bytes5(uint40(residualPurchaseTimeBufferHours)) << 16) | (bytes5(uint40(cashWithholdingBuffer10BPS)) << 24) | (bytes5(uint40(liquidationHaircutPercentage)) << 32)); // Set the parameters context.nTokenParameters = parameters; } /// @notice Retrieves the nToken supply factors without any updates or calculations function getStoredNTokenSupplyFactors(address tokenAddress) internal view returns ( uint256 totalSupply, uint256 integralTotalSupply, uint256 lastSupplyChangeTime ) { mapping(address => nTokenTotalSupplyStorage) storage store = LibStorage.getNTokenTotalSupplyStorage(); nTokenTotalSupplyStorage storage nTokenStorage = store[tokenAddress]; totalSupply = nTokenStorage.totalSupply; // NOTE: DO NOT USE THIS RETURNED VALUE FOR CALCULATING INCENTIVES. The integral total supply // must be updated given the block time. Use `calculateIntegralTotalSupply` instead integralTotalSupply = nTokenStorage.integralTotalSupply; lastSupplyChangeTime = nTokenStorage.lastSupplyChangeTime; } /// @notice Retrieves stored total supply factors and function calculateIntegralTotalSupply(address tokenAddress, uint256 blockTime) internal view returns ( uint256 totalSupply, uint256 integralTotalSupply, uint256 lastSupplyChangeTime ) { ( totalSupply, integralTotalSupply, lastSupplyChangeTime ) = getStoredNTokenSupplyFactors(tokenAddress); // Initialize last supply change time if it has not been set. if (lastSupplyChangeTime == 0) lastSupplyChangeTime = blockTime; require(blockTime >= lastSupplyChangeTime); // dev: invalid block time // Add to the integral total supply the total supply of tokens multiplied by the time that the total supply // has been the value. This will part of the numerator for the average total supply calculation during // minting incentives. integralTotalSupply = uint256(int256(integralTotalSupply).add( int256(totalSupply).mul(int256(blockTime - lastSupplyChangeTime)) )); require(integralTotalSupply >= 0 && integralTotalSupply < type(uint128).max); // dev: integral total supply overflow require(blockTime < type(uint32).max); // dev: last supply change supply overflow } /// @notice Updates the nToken token supply amount when minting or redeeming. function changeNTokenSupply( address tokenAddress, int256 netChange, uint256 blockTime ) internal returns (uint256) { ( uint256 totalSupply, uint256 integralTotalSupply, /* uint256 lastSupplyChangeTime */ ) = calculateIntegralTotalSupply(tokenAddress, blockTime); if (netChange != 0) { // If the totalSupply will change then we store the new total supply, the integral total supply and the // current block time. We know that this int256 conversion will not overflow because totalSupply is stored // as a uint96 and checked in the next line. int256 newTotalSupply = int256(totalSupply).add(netChange); require(newTotalSupply >= 0 && uint256(newTotalSupply) < type(uint96).max); // dev: nToken supply overflow mapping(address => nTokenTotalSupplyStorage) storage store = LibStorage.getNTokenTotalSupplyStorage(); nTokenTotalSupplyStorage storage nTokenStorage = store[tokenAddress]; nTokenStorage.totalSupply = uint96(newTotalSupply); // NOTE: overflows checked in calculateIntegralTotalSupply nTokenStorage.integralTotalSupply = uint128(integralTotalSupply); nTokenStorage.lastSupplyChangeTime = uint32(blockTime); } return integralTotalSupply; } function setIncentiveEmissionRate(address tokenAddress, uint32 newEmissionsRate) internal { mapping(address => nTokenContext) storage store = LibStorage.getNTokenContextStorage(); nTokenContext storage context = store[tokenAddress]; context.incentiveAnnualEmissionRate = newEmissionsRate; } function setArrayLengthAndInitializedTime( address tokenAddress, uint8 arrayLength, uint256 lastInitializedTime ) internal { require(lastInitializedTime >= 0 && uint256(lastInitializedTime) < type(uint32).max); // dev: next settle time overflow mapping(address => nTokenContext) storage store = LibStorage.getNTokenContextStorage(); nTokenContext storage context = store[tokenAddress]; context.lastInitializedTime = uint32(lastInitializedTime); context.assetArrayLength = arrayLength; } /// @notice Returns the array of deposit shares and leverage thresholds for nTokens function getDepositParameters(uint256 currencyId, uint256 maxMarketIndex) internal view returns (int256[] memory depositShares, int256[] memory leverageThresholds) { mapping(uint256 => uint32[NUM_NTOKEN_MARKET_FACTORS]) storage store = LibStorage.getNTokenDepositStorage(); uint32[NUM_NTOKEN_MARKET_FACTORS] storage depositParameters = store[currencyId]; (depositShares, leverageThresholds) = _getParameters(depositParameters, maxMarketIndex, false); } /// @notice Sets the deposit parameters /// @dev We pack the values in alternating between the two parameters into either one or two // storage slots depending on the number of markets. This is to save storage reads when we use the parameters. function setDepositParameters( uint256 currencyId, uint32[] calldata depositShares, uint32[] calldata leverageThresholds ) internal { require( depositShares.length <= Constants.MAX_TRADED_MARKET_INDEX, "PT: deposit share length" ); require(depositShares.length == leverageThresholds.length, "PT: leverage share length"); uint256 shareSum; for (uint256 i; i < depositShares.length; i++) { // This cannot overflow in uint 256 with 9 max slots shareSum = shareSum + depositShares[i]; require( leverageThresholds[i] > 0 && leverageThresholds[i] < Constants.RATE_PRECISION, "PT: leverage threshold" ); } // Total deposit share must add up to 100% require(shareSum == uint256(Constants.DEPOSIT_PERCENT_BASIS), "PT: deposit shares sum"); mapping(uint256 => uint32[NUM_NTOKEN_MARKET_FACTORS]) storage store = LibStorage.getNTokenDepositStorage(); uint32[NUM_NTOKEN_MARKET_FACTORS] storage depositParameters = store[currencyId]; _setParameters(depositParameters, depositShares, leverageThresholds); } /// @notice Sets the initialization parameters for the markets, these are read only when markets /// are initialized function setInitializationParameters( uint256 currencyId, uint32[] calldata annualizedAnchorRates, uint32[] calldata proportions ) internal { require(annualizedAnchorRates.length <= Constants.MAX_TRADED_MARKET_INDEX, "PT: annualized anchor rates length"); require(proportions.length == annualizedAnchorRates.length, "PT: proportions length"); for (uint256 i; i < proportions.length; i++) { // Proportions must be between zero and the rate precision require(annualizedAnchorRates[i] > 0, "NT: anchor rate zero"); require( proportions[i] > 0 && proportions[i] < Constants.RATE_PRECISION, "PT: invalid proportion" ); } mapping(uint256 => uint32[NUM_NTOKEN_MARKET_FACTORS]) storage store = LibStorage.getNTokenInitStorage(); uint32[NUM_NTOKEN_MARKET_FACTORS] storage initParameters = store[currencyId]; _setParameters(initParameters, annualizedAnchorRates, proportions); } /// @notice Returns the array of initialization parameters for a given currency. function getInitializationParameters(uint256 currencyId, uint256 maxMarketIndex) internal view returns (int256[] memory annualizedAnchorRates, int256[] memory proportions) { mapping(uint256 => uint32[NUM_NTOKEN_MARKET_FACTORS]) storage store = LibStorage.getNTokenInitStorage(); uint32[NUM_NTOKEN_MARKET_FACTORS] storage initParameters = store[currencyId]; (annualizedAnchorRates, proportions) = _getParameters(initParameters, maxMarketIndex, true); } function _getParameters( uint32[NUM_NTOKEN_MARKET_FACTORS] storage slot, uint256 maxMarketIndex, bool noUnset ) private view returns (int256[] memory, int256[] memory) { uint256 index = 0; int256[] memory array1 = new int256[](maxMarketIndex); int256[] memory array2 = new int256[](maxMarketIndex); for (uint256 i; i < maxMarketIndex; i++) { array1[i] = slot[index]; index++; array2[i] = slot[index]; index++; if (noUnset) { require(array1[i] > 0 && array2[i] > 0, "PT: init value zero"); } } return (array1, array2); } function _setParameters( uint32[NUM_NTOKEN_MARKET_FACTORS] storage slot, uint32[] calldata array1, uint32[] calldata array2 ) private { uint256 index = 0; for (uint256 i = 0; i < array1.length; i++) { slot[index] = array1[i]; index++; slot[index] = array2[i]; index++; } } function loadNTokenPortfolioNoCashGroup(nTokenPortfolio memory nToken, uint16 currencyId) internal view { nToken.tokenAddress = nTokenAddress(currencyId); // prettier-ignore ( /* currencyId */, /* incentiveRate */, uint256 lastInitializedTime, uint8 assetArrayLength, bytes5 parameters ) = getNTokenContext(nToken.tokenAddress); // prettier-ignore ( uint256 totalSupply, /* integralTotalSupply */, /* lastSupplyChangeTime */ ) = getStoredNTokenSupplyFactors(nToken.tokenAddress); nToken.lastInitializedTime = lastInitializedTime; nToken.totalSupply = int256(totalSupply); nToken.parameters = parameters; nToken.portfolioState = PortfolioHandler.buildPortfolioState( nToken.tokenAddress, assetArrayLength, 0 ); // prettier-ignore ( nToken.cashBalance, /* nTokenBalance */, /* lastClaimTime */, /* lastClaimIntegralSupply */ ) = BalanceHandler.getBalanceStorage(nToken.tokenAddress, currencyId); } /// @notice Uses buildCashGroupStateful function loadNTokenPortfolioStateful(nTokenPortfolio memory nToken, uint16 currencyId) internal { loadNTokenPortfolioNoCashGroup(nToken, currencyId); nToken.cashGroup = CashGroup.buildCashGroupStateful(currencyId); } /// @notice Uses buildCashGroupView function loadNTokenPortfolioView(nTokenPortfolio memory nToken, uint16 currencyId) internal view { loadNTokenPortfolioNoCashGroup(nToken, currencyId); nToken.cashGroup = CashGroup.buildCashGroupView(currencyId); } /// @notice Returns the next settle time for the nToken which is 1 quarter away function getNextSettleTime(nTokenPortfolio memory nToken) internal pure returns (uint256) { if (nToken.lastInitializedTime == 0) return 0; return DateTime.getReferenceTime(nToken.lastInitializedTime) + Constants.QUARTER; } /// @notice Returns the nToken present value denominated in asset terms. function getNTokenAssetPV(nTokenPortfolio memory nToken, uint256 blockTime) internal view returns (int256) { int256 totalAssetPV; int256 totalUnderlyingPV; { uint256 nextSettleTime = getNextSettleTime(nToken); // If the first asset maturity has passed (the 3 month), this means that all the LTs must // be settled except the 6 month (which is now the 3 month). We don't settle LTs except in // initialize markets so we calculate the cash value of the portfolio here. if (nextSettleTime <= blockTime) { // NOTE: this condition should only be present for a very short amount of time, which is the window between // when the markets are no longer tradable at quarter end and when the new markets have been initialized. // We time travel back to one second before maturity to value the liquidity tokens. Although this value is // not strictly correct the different should be quite slight. We do this to ensure that free collateral checks // for withdraws and liquidations can still be processed. If this condition persists for a long period of time then // the entire protocol will have serious problems as markets will not be tradable. blockTime = nextSettleTime - 1; } } // Since we are not doing a risk adjusted valuation here we do not need to net off residual fCash // balances in the future before discounting to present. If we did, then the ifCash assets would // have to be in the portfolio array first. PV here is denominated in asset cash terms, not in // underlying terms. { MarketParameters memory market; for (uint256 i; i < nToken.portfolioState.storedAssets.length; i++) { // NOTE: getLiquidityTokenValue can rewrite fCash values in memory, however, that does not // happen in this call because there are no fCash values in the nToken portfolio. (int256 assetCashClaim, int256 pv) = AssetHandler.getLiquidityTokenValue( i, nToken.cashGroup, market, nToken.portfolioState.storedAssets, blockTime, false ); totalAssetPV = totalAssetPV.add(assetCashClaim); totalUnderlyingPV = totalUnderlyingPV.add(pv); } } // Then iterate over bitmapped assets and get present value // prettier-ignore ( int256 bitmapPv, /* hasDebt */ ) = BitmapAssetsHandler.getifCashNetPresentValue( nToken.tokenAddress, nToken.cashGroup.currencyId, nToken.lastInitializedTime, blockTime, nToken.cashGroup, false ); totalUnderlyingPV = totalUnderlyingPV.add(bitmapPv); // Return the total present value denominated in asset terms totalAssetPV = totalAssetPV .add(nToken.cashGroup.assetRate.convertFromUnderlying(totalUnderlyingPV)) .add(nToken.cashBalance); return totalAssetPV; } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../../math/SafeInt256.sol"; import "../../global/LibStorage.sol"; import "../../global/Types.sol"; import "../../global/Constants.sol"; import "interfaces/compound/CErc20Interface.sol"; import "interfaces/compound/CEtherInterface.sol"; import "interfaces/IEIP20NonStandard.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; /// @notice Handles all external token transfers and events library TokenHandler { using SafeInt256 for int256; using SafeMath for uint256; function setMaxCollateralBalance(uint256 currencyId, uint72 maxCollateralBalance) internal { mapping(uint256 => mapping(bool => TokenStorage)) storage store = LibStorage.getTokenStorage(); TokenStorage storage tokenStorage = store[currencyId][false]; tokenStorage.maxCollateralBalance = maxCollateralBalance; } function getAssetToken(uint256 currencyId) internal view returns (Token memory) { return _getToken(currencyId, false); } function getUnderlyingToken(uint256 currencyId) internal view returns (Token memory) { return _getToken(currencyId, true); } /// @notice Gets token data for a particular currency id, if underlying is set to true then returns /// the underlying token. (These may not always exist) function _getToken(uint256 currencyId, bool underlying) private view returns (Token memory) { mapping(uint256 => mapping(bool => TokenStorage)) storage store = LibStorage.getTokenStorage(); TokenStorage storage tokenStorage = store[currencyId][underlying]; return Token({ tokenAddress: tokenStorage.tokenAddress, hasTransferFee: tokenStorage.hasTransferFee, // No overflow, restricted on storage decimals: int256(10**tokenStorage.decimalPlaces), tokenType: tokenStorage.tokenType, maxCollateralBalance: tokenStorage.maxCollateralBalance }); } /// @notice Sets a token for a currency id. function setToken( uint256 currencyId, bool underlying, TokenStorage memory tokenStorage ) internal { mapping(uint256 => mapping(bool => TokenStorage)) storage store = LibStorage.getTokenStorage(); if (tokenStorage.tokenType == TokenType.Ether && currencyId == Constants.ETH_CURRENCY_ID) { // Hardcoded parameters for ETH just to make sure we don't get it wrong. TokenStorage storage ts = store[currencyId][true]; ts.tokenAddress = address(0); ts.hasTransferFee = false; ts.tokenType = TokenType.Ether; ts.decimalPlaces = Constants.ETH_DECIMAL_PLACES; ts.maxCollateralBalance = 0; return; } // Check token address require(tokenStorage.tokenAddress != address(0), "TH: address is zero"); // Once a token is set we cannot override it. In the case that we do need to do change a token address // then we should explicitly upgrade this method to allow for a token to be changed. Token memory token = _getToken(currencyId, underlying); require( token.tokenAddress == tokenStorage.tokenAddress || token.tokenAddress == address(0), "TH: token cannot be reset" ); require(0 < tokenStorage.decimalPlaces && tokenStorage.decimalPlaces <= Constants.MAX_DECIMAL_PLACES, "TH: invalid decimals"); // Validate token type require(tokenStorage.tokenType != TokenType.Ether); // dev: ether can only be set once if (underlying) { // Underlying tokens cannot have max collateral balances, the contract only has a balance temporarily // during mint and redeem actions. require(tokenStorage.maxCollateralBalance == 0); // dev: underlying cannot have max collateral balance require(tokenStorage.tokenType == TokenType.UnderlyingToken); // dev: underlying token inconsistent } else { require(tokenStorage.tokenType != TokenType.UnderlyingToken); // dev: underlying token inconsistent } if (tokenStorage.tokenType == TokenType.cToken) { // Set the approval for the underlying so that we can mint cTokens Token memory underlyingToken = getUnderlyingToken(currencyId); // ERC20 tokens should return true on success for an approval, but Tether // does not return a value here so we use the NonStandard interface here to // check that the approval was successful. IEIP20NonStandard(underlyingToken.tokenAddress).approve( tokenStorage.tokenAddress, type(uint256).max ); checkReturnCode(); } store[currencyId][underlying] = tokenStorage; } /// @notice This method only works with cTokens, it's unclear how we can make this more generic function mint(Token memory token, uint256 underlyingAmountExternal) internal returns (int256) { uint256 startingBalance = IERC20(token.tokenAddress).balanceOf(address(this)); uint256 success; if (token.tokenType == TokenType.cToken) { success = CErc20Interface(token.tokenAddress).mint(underlyingAmountExternal); } else if (token.tokenType == TokenType.cETH) { // Reverts on error CEtherInterface(token.tokenAddress).mint{value: msg.value}(); } else { revert(); // dev: non mintable token } require(success == Constants.COMPOUND_RETURN_CODE_NO_ERROR, "Mint"); uint256 endingBalance = IERC20(token.tokenAddress).balanceOf(address(this)); // This is the starting and ending balance in external precision return SafeInt256.toInt(endingBalance.sub(startingBalance)); } function redeem( Token memory assetToken, Token memory underlyingToken, uint256 assetAmountExternal ) internal returns (int256) { uint256 startingBalance; if (assetToken.tokenType == TokenType.cETH) { startingBalance = address(this).balance; } else if (assetToken.tokenType == TokenType.cToken) { startingBalance = IERC20(underlyingToken.tokenAddress).balanceOf(address(this)); } else { revert(); // dev: non redeemable failure } uint256 success = CErc20Interface(assetToken.tokenAddress).redeem(assetAmountExternal); require(success == Constants.COMPOUND_RETURN_CODE_NO_ERROR, "Redeem"); uint256 endingBalance; if (assetToken.tokenType == TokenType.cETH) { endingBalance = address(this).balance; } else { endingBalance = IERC20(underlyingToken.tokenAddress).balanceOf(address(this)); } // Underlying token external precision return SafeInt256.toInt(endingBalance.sub(startingBalance)); } /// @notice Handles transfers into and out of the system denominated in the external token decimal /// precision. function transfer( Token memory token, address account, int256 netTransferExternal ) internal returns (int256) { if (netTransferExternal > 0) { // Deposits must account for transfer fees. netTransferExternal = _deposit(token, account, uint256(netTransferExternal)); } else if (token.tokenType == TokenType.Ether) { require(netTransferExternal <= 0); // dev: cannot deposit ether address payable accountPayable = payable(account); // This does not work with contracts, but is reentrancy safe. If contracts want to withdraw underlying // ETH they will have to withdraw the cETH token and then redeem it manually. accountPayable.transfer(uint256(netTransferExternal.neg())); } else { safeTransferOut( token.tokenAddress, account, // netTransferExternal is zero or negative here uint256(netTransferExternal.neg()) ); } return netTransferExternal; } /// @notice Handles token deposits into Notional. If there is a transfer fee then we must /// calculate the net balance after transfer. Amounts are denominated in the destination token's /// precision. function _deposit( Token memory token, address account, uint256 amount ) private returns (int256) { uint256 startingBalance; uint256 endingBalance; if (token.hasTransferFee) { startingBalance = IERC20(token.tokenAddress).balanceOf(address(this)); } safeTransferIn(token.tokenAddress, account, amount); if (token.hasTransferFee || token.maxCollateralBalance > 0) { endingBalance = IERC20(token.tokenAddress).balanceOf(address(this)); } if (token.maxCollateralBalance > 0) { int256 internalPrecisionBalance = convertToInternal(token, SafeInt256.toInt(endingBalance)); // Max collateral balance is stored as uint72, no overflow require(internalPrecisionBalance <= SafeInt256.toInt(token.maxCollateralBalance)); // dev: over max collateral balance } // Math is done in uint inside these statements and will revert on negative if (token.hasTransferFee) { return SafeInt256.toInt(endingBalance.sub(startingBalance)); } else { return SafeInt256.toInt(amount); } } function convertToInternal(Token memory token, int256 amount) internal pure returns (int256) { // If token decimals > INTERNAL_TOKEN_PRECISION: // on deposit: resulting dust will accumulate to protocol // on withdraw: protocol may lose dust amount. However, withdraws are only calculated based // on a conversion from internal token precision to external token precision so therefore dust // amounts cannot be specified for withdraws. // If token decimals < INTERNAL_TOKEN_PRECISION then this will add zeros to the // end of amount and will not result in dust. if (token.decimals == Constants.INTERNAL_TOKEN_PRECISION) return amount; return amount.mul(Constants.INTERNAL_TOKEN_PRECISION).div(token.decimals); } function convertToExternal(Token memory token, int256 amount) internal pure returns (int256) { if (token.decimals == Constants.INTERNAL_TOKEN_PRECISION) return amount; // If token decimals > INTERNAL_TOKEN_PRECISION then this will increase amount // by adding a number of zeros to the end and will not result in dust. // If token decimals < INTERNAL_TOKEN_PRECISION: // on deposit: Deposits are specified in external token precision and there is no loss of precision when // tokens are converted from external to internal precision // on withdraw: this calculation will round down such that the protocol retains the residual cash balance return amount.mul(token.decimals).div(Constants.INTERNAL_TOKEN_PRECISION); } function transferIncentive(address account, uint256 tokensToTransfer) internal { safeTransferOut(Constants.NOTE_TOKEN_ADDRESS, account, tokensToTransfer); } function safeTransferOut( address token, address account, uint256 amount ) private { IEIP20NonStandard(token).transfer(account, amount); checkReturnCode(); } function safeTransferIn( address token, address account, uint256 amount ) private { IEIP20NonStandard(token).transferFrom(account, address(this), amount); checkReturnCode(); } function checkReturnCode() private pure { bool success; uint256[1] memory result; assembly { switch returndatasize() case 0 { // This is a non-standard ERC-20 success := 1 // set success to true } case 32 { // This is a compliant ERC-20 returndatacopy(result, 0, 32) success := mload(result) // Set `success = returndata` of external call } default { // This is an excessively non-compliant ERC-20, revert. revert(0, 0) } } require(success, "ERC20"); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "./Types.sol"; /** * @notice Storage layout for the system. Do not change this file once deployed, future storage * layouts must inherit this and increment the version number. */ contract StorageLayoutV1 { // The current maximum currency id uint16 internal maxCurrencyId; // Sets the state of liquidations being enabled during a paused state. Each of the four lower // bits can be turned on to represent one of the liquidation types being enabled. bytes1 internal liquidationEnabledState; // Set to true once the system has been initialized bool internal hasInitialized; /* Authentication Mappings */ // This is set to the timelock contract to execute governance functions address public owner; // This is set to an address of a router that can only call governance actions address public pauseRouter; // This is set to an address of a router that can only call governance actions address public pauseGuardian; // On upgrades this is set in the case that the pause router is used to pass the rollback check address internal rollbackRouterImplementation; // A blanket allowance for a spender to transfer any of an account's nTokens. This would allow a user // to set an allowance on all nTokens for a particular integrating contract system. // owner => spender => transferAllowance mapping(address => mapping(address => uint256)) internal nTokenWhitelist; // Individual transfer allowances for nTokens used for ERC20 // owner => spender => currencyId => transferAllowance mapping(address => mapping(address => mapping(uint16 => uint256))) internal nTokenAllowance; // Transfer operators // Mapping from a global ERC1155 transfer operator contract to an approval value for it mapping(address => bool) internal globalTransferOperator; // Mapping from an account => operator => approval status for that operator. This is a specific // approval between two addresses for ERC1155 transfers. mapping(address => mapping(address => bool)) internal accountAuthorizedTransferOperator; // Approval for a specific contract to use the `batchBalanceAndTradeActionWithCallback` method in // BatchAction.sol, can only be set by governance mapping(address => bool) internal authorizedCallbackContract; // Reverse mapping from token addresses to currency ids, only used for referencing in views // and checking for duplicate token listings. mapping(address => uint16) internal tokenAddressToCurrencyId; // Reentrancy guard uint256 internal reentrancyStatus; } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "./Types.sol"; import "./Constants.sol"; library LibStorage { /// @dev Offset for the initial slot in lib storage, gives us this number of storage slots /// available in StorageLayoutV1 and all subsequent storage layouts that inherit from it. uint256 private constant STORAGE_SLOT_BASE = 1000000; /// @dev Set to MAX_TRADED_MARKET_INDEX * 2, Solidity does not allow assigning constants from imported values uint256 private constant NUM_NTOKEN_MARKET_FACTORS = 14; /// @dev Theoretical maximum for MAX_PORTFOLIO_ASSETS, however, we limit this to MAX_TRADED_MARKET_INDEX /// in practice. It is possible to exceed that value during liquidation up to 14 potential assets. uint256 private constant MAX_PORTFOLIO_ASSETS = 16; /// @dev Storage IDs for storage buckets. Each id maps to an internal storage /// slot used for a particular mapping /// WARNING: APPEND ONLY enum StorageId { Unused, AccountStorage, nTokenContext, nTokenAddress, nTokenDeposit, nTokenInitialization, Balance, Token, SettlementRate, CashGroup, Market, AssetsBitmap, ifCashBitmap, PortfolioArray, nTokenTotalSupply, AssetRate, ExchangeRate } /// @dev Mapping from an account address to account context function getAccountStorage() internal pure returns (mapping(address => AccountContext) storage store) { uint256 slot = _getStorageSlot(StorageId.AccountStorage); assembly { store.slot := slot } } /// @dev Mapping from an nToken address to nTokenContext function getNTokenContextStorage() internal pure returns (mapping(address => nTokenContext) storage store) { uint256 slot = _getStorageSlot(StorageId.nTokenContext); assembly { store.slot := slot } } /// @dev Mapping from currency id to nTokenAddress function getNTokenAddressStorage() internal pure returns (mapping(uint256 => address) storage store) { uint256 slot = _getStorageSlot(StorageId.nTokenAddress); assembly { store.slot := slot } } /// @dev Mapping from currency id to uint32 fixed length array of /// deposit factors. Deposit shares and leverage thresholds are stored striped to /// reduce the number of storage reads. function getNTokenDepositStorage() internal pure returns (mapping(uint256 => uint32[NUM_NTOKEN_MARKET_FACTORS]) storage store) { uint256 slot = _getStorageSlot(StorageId.nTokenDeposit); assembly { store.slot := slot } } /// @dev Mapping from currency id to fixed length array of initialization factors, /// stored striped like deposit shares. function getNTokenInitStorage() internal pure returns (mapping(uint256 => uint32[NUM_NTOKEN_MARKET_FACTORS]) storage store) { uint256 slot = _getStorageSlot(StorageId.nTokenInitialization); assembly { store.slot := slot } } /// @dev Mapping from account to currencyId to it's balance storage for that currency function getBalanceStorage() internal pure returns (mapping(address => mapping(uint256 => BalanceStorage)) storage store) { uint256 slot = _getStorageSlot(StorageId.Balance); assembly { store.slot := slot } } /// @dev Mapping from currency id to a boolean for underlying or asset token to /// the TokenStorage function getTokenStorage() internal pure returns (mapping(uint256 => mapping(bool => TokenStorage)) storage store) { uint256 slot = _getStorageSlot(StorageId.Token); assembly { store.slot := slot } } /// @dev Mapping from currency id to maturity to its corresponding SettlementRate function getSettlementRateStorage() internal pure returns (mapping(uint256 => mapping(uint256 => SettlementRateStorage)) storage store) { uint256 slot = _getStorageSlot(StorageId.SettlementRate); assembly { store.slot := slot } } /// @dev Mapping from currency id to maturity to its tightly packed cash group parameters function getCashGroupStorage() internal pure returns (mapping(uint256 => bytes32) storage store) { uint256 slot = _getStorageSlot(StorageId.CashGroup); assembly { store.slot := slot } } /// @dev Mapping from currency id to maturity to settlement date for a market function getMarketStorage() internal pure returns (mapping(uint256 => mapping(uint256 => mapping(uint256 => MarketStorage))) storage store) { uint256 slot = _getStorageSlot(StorageId.Market); assembly { store.slot := slot } } /// @dev Mapping from account to currency id to its assets bitmap function getAssetsBitmapStorage() internal pure returns (mapping(address => mapping(uint256 => bytes32)) storage store) { uint256 slot = _getStorageSlot(StorageId.AssetsBitmap); assembly { store.slot := slot } } /// @dev Mapping from account to currency id to its maturity to its corresponding ifCash balance function getifCashBitmapStorage() internal pure returns (mapping(address => mapping(uint256 => mapping(uint256 => ifCashStorage))) storage store) { uint256 slot = _getStorageSlot(StorageId.ifCashBitmap); assembly { store.slot := slot } } /// @dev Mapping from account to its fixed length array of portfolio assets function getPortfolioArrayStorage() internal pure returns (mapping(address => PortfolioAssetStorage[MAX_PORTFOLIO_ASSETS]) storage store) { uint256 slot = _getStorageSlot(StorageId.PortfolioArray); assembly { store.slot := slot } } /// @dev Mapping from nToken address to its total supply values function getNTokenTotalSupplyStorage() internal pure returns (mapping(address => nTokenTotalSupplyStorage) storage store) { uint256 slot = _getStorageSlot(StorageId.nTokenTotalSupply); assembly { store.slot := slot } } /// @dev Returns the exchange rate between an underlying currency and asset for trading /// and free collateral. Mapping is from currency id to rate storage object. function getAssetRateStorage() internal pure returns (mapping(uint256 => AssetRateStorage) storage store) { uint256 slot = _getStorageSlot(StorageId.AssetRate); assembly { store.slot := slot } } /// @dev Returns the exchange rate between an underlying currency and ETH for free /// collateral purposes. Mapping is from currency id to rate storage object. function getExchangeRateStorage() internal pure returns (mapping(uint256 => ETHRateStorage) storage store) { uint256 slot = _getStorageSlot(StorageId.ExchangeRate); assembly { store.slot := slot } } /// @dev Get the storage slot given a storage ID. /// @param storageId An entry in `StorageId` /// @return slot The storage slot. function _getStorageSlot(StorageId storageId) private pure returns (uint256 slot) { // This should never overflow with a reasonable `STORAGE_SLOT_EXP` // because Solidity will do a range check on `storageId` during the cast. return uint256(storageId) + STORAGE_SLOT_BASE; } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "interfaces/chainlink/AggregatorV2V3Interface.sol"; import "interfaces/notional/AssetRateAdapter.sol"; /// @notice Different types of internal tokens /// - UnderlyingToken: underlying asset for a cToken (except for Ether) /// - cToken: Compound interest bearing token /// - cETH: Special handling for cETH tokens /// - Ether: the one and only /// - NonMintable: tokens that do not have an underlying (therefore not cTokens) enum TokenType {UnderlyingToken, cToken, cETH, Ether, NonMintable} /// @notice Specifies the different trade action types in the system. Each trade action type is /// encoded in a tightly packed bytes32 object. Trade action type is the first big endian byte of the /// 32 byte trade action object. The schemas for each trade action type are defined below. enum TradeActionType { // (uint8 TradeActionType, uint8 MarketIndex, uint88 fCashAmount, uint32 minImpliedRate, uint120 unused) Lend, // (uint8 TradeActionType, uint8 MarketIndex, uint88 fCashAmount, uint32 maxImpliedRate, uint128 unused) Borrow, // (uint8 TradeActionType, uint8 MarketIndex, uint88 assetCashAmount, uint32 minImpliedRate, uint32 maxImpliedRate, uint88 unused) AddLiquidity, // (uint8 TradeActionType, uint8 MarketIndex, uint88 tokenAmount, uint32 minImpliedRate, uint32 maxImpliedRate, uint88 unused) RemoveLiquidity, // (uint8 TradeActionType, uint32 Maturity, int88 fCashResidualAmount, uint128 unused) PurchaseNTokenResidual, // (uint8 TradeActionType, address CounterpartyAddress, int88 fCashAmountToSettle) SettleCashDebt } /// @notice Specifies different deposit actions that can occur during BalanceAction or BalanceActionWithTrades enum DepositActionType { // No deposit action None, // Deposit asset cash, depositActionAmount is specified in asset cash external precision DepositAsset, // Deposit underlying tokens that are mintable to asset cash, depositActionAmount is specified in underlying token // external precision DepositUnderlying, // Deposits specified asset cash external precision amount into an nToken and mints the corresponding amount of // nTokens into the account DepositAssetAndMintNToken, // Deposits specified underlying in external precision, mints asset cash, and uses that asset cash to mint nTokens DepositUnderlyingAndMintNToken, // Redeems an nToken balance to asset cash. depositActionAmount is specified in nToken precision. Considered a deposit action // because it deposits asset cash into an account. If there are fCash residuals that cannot be sold off, will revert. RedeemNToken, // Converts specified amount of asset cash balance already in Notional to nTokens. depositActionAmount is specified in // Notional internal 8 decimal precision. ConvertCashToNToken } /// @notice Used internally for PortfolioHandler state enum AssetStorageState {NoChange, Update, Delete, RevertIfStored} /****** Calldata objects ******/ /// @notice Defines a balance action for batchAction struct BalanceAction { // Deposit action to take (if any) DepositActionType actionType; uint16 currencyId; // Deposit action amount must correspond to the depositActionType, see documentation above. uint256 depositActionAmount; // Withdraw an amount of asset cash specified in Notional internal 8 decimal precision uint256 withdrawAmountInternalPrecision; // If set to true, will withdraw entire cash balance. Useful if there may be an unknown amount of asset cash // residual left from trading. bool withdrawEntireCashBalance; // If set to true, will redeem asset cash to the underlying token on withdraw. bool redeemToUnderlying; } /// @notice Defines a balance action with a set of trades to do as well struct BalanceActionWithTrades { DepositActionType actionType; uint16 currencyId; uint256 depositActionAmount; uint256 withdrawAmountInternalPrecision; bool withdrawEntireCashBalance; bool redeemToUnderlying; // Array of tightly packed 32 byte objects that represent trades. See TradeActionType documentation bytes32[] trades; } /****** In memory objects ******/ /// @notice Internal object that represents settled cash balances struct SettleAmount { uint256 currencyId; int256 netCashChange; } /// @notice Internal object that represents a token struct Token { address tokenAddress; bool hasTransferFee; int256 decimals; TokenType tokenType; uint256 maxCollateralBalance; } /// @notice Internal object that represents an nToken portfolio struct nTokenPortfolio { CashGroupParameters cashGroup; PortfolioState portfolioState; int256 totalSupply; int256 cashBalance; uint256 lastInitializedTime; bytes6 parameters; address tokenAddress; } /// @notice Internal object used during liquidation struct LiquidationFactors { address account; // Aggregate free collateral of the account denominated in ETH underlying, 8 decimal precision int256 netETHValue; // Amount of net local currency asset cash before haircuts and buffers available int256 localAssetAvailable; // Amount of net collateral currency asset cash before haircuts and buffers available int256 collateralAssetAvailable; // Haircut value of nToken holdings denominated in asset cash, will be local or collateral nTokens based // on liquidation type int256 nTokenHaircutAssetValue; // nToken parameters for calculating liquidation amount bytes6 nTokenParameters; // ETH exchange rate from local currency to ETH ETHRate localETHRate; // ETH exchange rate from collateral currency to ETH ETHRate collateralETHRate; // Asset rate for the local currency, used in cross currency calculations to calculate local asset cash required AssetRateParameters localAssetRate; // Used during currency liquidations if the account has liquidity tokens CashGroupParameters collateralCashGroup; // Used during currency liquidations if it is only a calculation, defaults to false bool isCalculation; } /// @notice Internal asset array portfolio state struct PortfolioState { // Array of currently stored assets PortfolioAsset[] storedAssets; // Array of new assets to add PortfolioAsset[] newAssets; uint256 lastNewAssetIndex; // Holds the length of stored assets after accounting for deleted assets uint256 storedAssetLength; } /// @notice In memory ETH exchange rate used during free collateral calculation. struct ETHRate { // The decimals (i.e. 10^rateDecimalPlaces) of the exchange rate, defined by the rate oracle int256 rateDecimals; // The exchange rate from base to ETH (if rate invert is required it is already done) int256 rate; // Amount of buffer as a multiple with a basis of 100 applied to negative balances. int256 buffer; // Amount of haircut as a multiple with a basis of 100 applied to positive balances int256 haircut; // Liquidation discount as a multiple with a basis of 100 applied to the exchange rate // as an incentive given to liquidators. int256 liquidationDiscount; } /// @notice Internal object used to handle balance state during a transaction struct BalanceState { uint16 currencyId; // Cash balance stored in balance state at the beginning of the transaction int256 storedCashBalance; // nToken balance stored at the beginning of the transaction int256 storedNTokenBalance; // The net cash change as a result of asset settlement or trading int256 netCashChange; // Net asset transfers into or out of the account int256 netAssetTransferInternalPrecision; // Net token transfers into or out of the account int256 netNTokenTransfer; // Net token supply change from minting or redeeming int256 netNTokenSupplyChange; // The last time incentives were claimed for this currency uint256 lastClaimTime; // The last integral supply amount when tokens were claimed uint256 lastClaimIntegralSupply; } /// @dev Asset rate used to convert between underlying cash and asset cash struct AssetRateParameters { // Address of the asset rate oracle AssetRateAdapter rateOracle; // The exchange rate from base to quote (if invert is required it is already done) int256 rate; // The decimals of the underlying, the rate converts to the underlying decimals int256 underlyingDecimals; } /// @dev Cash group when loaded into memory struct CashGroupParameters { uint16 currencyId; uint256 maxMarketIndex; AssetRateParameters assetRate; bytes32 data; } /// @dev A portfolio asset when loaded in memory struct PortfolioAsset { // Asset currency id uint256 currencyId; uint256 maturity; // Asset type, fCash or liquidity token. uint256 assetType; // fCash amount or liquidity token amount int256 notional; // Used for managing portfolio asset state uint256 storageSlot; // The state of the asset for when it is written to storage AssetStorageState storageState; } /// @dev Market object as represented in memory struct MarketParameters { bytes32 storageSlot; uint256 maturity; // Total amount of fCash available for purchase in the market. int256 totalfCash; // Total amount of cash available for purchase in the market. int256 totalAssetCash; // Total amount of liquidity tokens (representing a claim on liquidity) in the market. int256 totalLiquidity; // This is the previous annualized interest rate in RATE_PRECISION that the market traded // at. This is used to calculate the rate anchor to smooth interest rates over time. uint256 lastImpliedRate; // Time lagged version of lastImpliedRate, used to value fCash assets at market rates while // remaining resistent to flash loan attacks. uint256 oracleRate; // This is the timestamp of the previous trade uint256 previousTradeTime; } /****** Storage objects ******/ /// @dev Token object in storage: /// 20 bytes for token address /// 1 byte for hasTransferFee /// 1 byte for tokenType /// 1 byte for tokenDecimals /// 9 bytes for maxCollateralBalance (may not always be set) struct TokenStorage { // Address of the token address tokenAddress; // Transfer fees will change token deposit behavior bool hasTransferFee; TokenType tokenType; uint8 decimalPlaces; // Upper limit on how much of this token the contract can hold at any time uint72 maxCollateralBalance; } /// @dev Exchange rate object as it is represented in storage, total storage is 25 bytes. struct ETHRateStorage { // Address of the rate oracle AggregatorV2V3Interface rateOracle; // The decimal places of precision that the rate oracle uses uint8 rateDecimalPlaces; // True of the exchange rate must be inverted bool mustInvert; // NOTE: both of these governance values are set with BUFFER_DECIMALS precision // Amount of buffer to apply to the exchange rate for negative balances. uint8 buffer; // Amount of haircut to apply to the exchange rate for positive balances uint8 haircut; // Liquidation discount in percentage point terms, 106 means a 6% discount uint8 liquidationDiscount; } /// @dev Asset rate oracle object as it is represented in storage, total storage is 21 bytes. struct AssetRateStorage { // Address of the rate oracle AssetRateAdapter rateOracle; // The decimal places of the underlying asset uint8 underlyingDecimalPlaces; } /// @dev Governance parameters for a cash group, total storage is 9 bytes + 7 bytes for liquidity token haircuts /// and 7 bytes for rate scalars, total of 23 bytes. Note that this is stored packed in the storage slot so there /// are no indexes stored for liquidityTokenHaircuts or rateScalars, maxMarketIndex is used instead to determine the /// length. struct CashGroupSettings { // Index of the AMMs on chain that will be made available. Idiosyncratic fCash // that is dated less than the longest AMM will be tradable. uint8 maxMarketIndex; // Time window in 5 minute increments that the rate oracle will be averaged over uint8 rateOracleTimeWindow5Min; // Total fees per trade, specified in BPS uint8 totalFeeBPS; // Share of the fees given to the protocol, denominated in percentage uint8 reserveFeeShare; // Debt buffer specified in 5 BPS increments uint8 debtBuffer5BPS; // fCash haircut specified in 5 BPS increments uint8 fCashHaircut5BPS; // If an account has a negative cash balance, it can be settled by incurring debt at the 3 month market. This // is the basis points for the penalty rate that will be added the current 3 month oracle rate. uint8 settlementPenaltyRate5BPS; // If an account has fCash that is being liquidated, this is the discount that the liquidator can purchase it for uint8 liquidationfCashHaircut5BPS; // If an account has fCash that is being liquidated, this is the discount that the liquidator can purchase it for uint8 liquidationDebtBuffer5BPS; // Liquidity token haircut applied to cash claims, specified as a percentage between 0 and 100 uint8[] liquidityTokenHaircuts; // Rate scalar used to determine the slippage of the market uint8[] rateScalars; } /// @dev Holds account level context information used to determine settlement and /// free collateral actions. Total storage is 28 bytes struct AccountContext { // Used to check when settlement must be triggered on an account uint40 nextSettleTime; // For lenders that never incur debt, we use this flag to skip the free collateral check. bytes1 hasDebt; // Length of the account's asset array uint8 assetArrayLength; // If this account has bitmaps set, this is the corresponding currency id uint16 bitmapCurrencyId; // 9 total active currencies possible (2 bytes each) bytes18 activeCurrencies; } /// @dev Holds nToken context information mapped via the nToken address, total storage is /// 16 bytes struct nTokenContext { // Currency id that the nToken represents uint16 currencyId; // Annual incentive emission rate denominated in WHOLE TOKENS (multiply by // INTERNAL_TOKEN_PRECISION to get the actual rate) uint32 incentiveAnnualEmissionRate; // The last block time at utc0 that the nToken was initialized at, zero if it // has never been initialized uint32 lastInitializedTime; // Length of the asset array, refers to the number of liquidity tokens an nToken // currently holds uint8 assetArrayLength; // Each byte is a specific nToken parameter bytes5 nTokenParameters; } /// @dev Holds account balance information, total storage 32 bytes struct BalanceStorage { // Number of nTokens held by the account uint80 nTokenBalance; // Last time the account claimed their nTokens uint32 lastClaimTime; // The total integral supply of the nToken at the last claim time packed into // 56 bits. There is some loss of precision here but it is acceptable uint56 packedLastClaimIntegralSupply; // Cash balance of the account int88 cashBalance; } /// @dev Holds information about a settlement rate, total storage 25 bytes struct SettlementRateStorage { uint40 blockTime; uint128 settlementRate; uint8 underlyingDecimalPlaces; } /// @dev Holds information about a market, total storage is 42 bytes so this spans /// two storage words struct MarketStorage { // Total fCash in the market uint80 totalfCash; // Total asset cash in the market uint80 totalAssetCash; // Last annualized interest rate the market traded at uint32 lastImpliedRate; // Last recorded oracle rate for the market uint32 oracleRate; // Last time a trade was made uint32 previousTradeTime; // This is stored in slot + 1 uint80 totalLiquidity; } struct ifCashStorage { // Notional amount of fCash at the slot, limited to int128 to allow for // future expansion int128 notional; } /// @dev A single portfolio asset in storage, total storage of 19 bytes struct PortfolioAssetStorage { // Currency Id for the asset uint16 currencyId; // Maturity of the asset uint40 maturity; // Asset type (fCash or Liquidity Token marker) uint8 assetType; // Notional int88 notional; } /// @dev nToken total supply factors for the nToken, includes factors related /// to claiming incentives, total storage 32 bytes struct nTokenTotalSupplyStorage { // Total supply of the nToken uint96 totalSupply; // Integral of the total supply used for calculating the average total supply uint128 integralTotalSupply; // Last timestamp the supply value changed, used for calculating the integralTotalSupply uint32 lastSupplyChangeTime; } /// @dev Used in view methods to return account balances in a developer friendly manner struct AccountBalance { uint16 currencyId; int256 cashBalance; int256 nTokenBalance; uint256 lastClaimTime; uint256 lastClaimIntegralSupply; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "../ERC1967/ERC1967Upgrade.sol"; /** * @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an * {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy. * * A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is * reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing * `UUPSUpgradeable` with a custom implementation of upgrades. * * The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism. * * _Available since v4.1._ */ abstract contract UUPSUpgradeable is ERC1967Upgrade { /** * @dev Upgrade the implementation of the proxy to `newImplementation`. * * Calls {_authorizeUpgrade}. * * Emits an {Upgraded} event. */ function upgradeTo(address newImplementation) external virtual { _authorizeUpgrade(newImplementation); _upgradeToAndCallSecure(newImplementation, bytes(""), false); } /** * @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call * encoded in `data`. * * Calls {_authorizeUpgrade}. * * Emits an {Upgraded} event. */ function upgradeToAndCall(address newImplementation, bytes memory data) external payable virtual { _authorizeUpgrade(newImplementation); _upgradeToAndCallSecure(newImplementation, data, true); } /** * @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by * {upgradeTo} and {upgradeToAndCall}. * * Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}. * * ```solidity * function _authorizeUpgrade(address) internal override onlyOwner {} * ``` */ function _authorizeUpgrade(address newImplementation) internal virtual; } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "interfaces/notional/nTokenERC20.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /// @notice ERC20 proxy for nToken contracts that forwards calls to the Router, all nToken /// balances and allowances are stored in at single address for gas efficiency. This contract /// is used simply for ERC20 compliance. contract nTokenERC20Proxy is IERC20 { /// @notice Will be "nToken {Underlying Token}.name()", therefore "USD Coin" will be /// nToken USD Coin string public name; /// @notice Will be "n{Underlying Token}.symbol()", therefore "USDC" will be "nUSDC" string public symbol; /// @notice Inherits from Constants.INTERNAL_TOKEN_PRECISION uint8 public constant decimals = 8; /// @notice Address of the notional proxy nTokenERC20 public immutable proxy; /// @notice Currency id that this nToken refers to uint16 public immutable currencyId; constructor( nTokenERC20 proxy_, uint16 currencyId_, string memory underlyingName_, string memory underlyingSymbol_ ) { proxy = proxy_; currencyId = currencyId_; name = string(abi.encodePacked("nToken ", underlyingName_)); symbol = string(abi.encodePacked("n", underlyingSymbol_)); } /// @notice Total number of tokens in circulation function totalSupply() external view override returns (uint256) { // Total supply is looked up via the token address return proxy.nTokenTotalSupply(address(this)); } /// @notice Get the number of tokens held by the `account` /// @param account The address of the account to get the balance of /// @return The number of tokens held function balanceOf(address account) external view override returns (uint256) { return proxy.nTokenBalanceOf(currencyId, account); } /// @notice Get the number of tokens `spender` is approved to spend on behalf of `account` /// @param account The address of the account holding the funds /// @param spender The address of the account spending the funds /// @return The number of tokens approved function allowance(address account, address spender) external view override returns (uint256) { return proxy.nTokenTransferAllowance(currencyId, account, spender); } /// @notice Approve `spender` to transfer up to `amount` from `src` /// @dev This will overwrite the approval amount for `spender` /// and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) /// emit:Approval /// @param spender The address of the account which may transfer tokens /// @param amount The number of tokens that are approved (2^256-1 means infinite) /// @return Whether or not the approval succeeded function approve(address spender, uint256 amount) external override returns (bool) { bool success = proxy.nTokenTransferApprove(currencyId, msg.sender, spender, amount); // Emit approvals here so that they come from the correct contract address if (success) emit Approval(msg.sender, spender, amount); return success; } /// @notice Transfer `amount` tokens from `msg.sender` to `to` /// @dev emit:Transfer /// @param to The address of the destination account /// @param amount The number of tokens to transfer /// @return Whether or not the transfer succeeded function transfer(address to, uint256 amount) external override returns (bool) { bool success = proxy.nTokenTransfer(currencyId, msg.sender, to, amount); // Emit transfer events here so they come from the correct contract if (success) emit Transfer(msg.sender, to, amount); return success; } /// @notice Transfer `amount` tokens from `from` to `to` /// @dev emit:Transfer emit:Approval /// @param from The address of the source account /// @param to The address of the destination account /// @param amount The number of tokens to transfer /// @return Whether or not the transfer succeeded function transferFrom( address from, address to, uint256 amount ) external override returns (bool) { bool success = proxy.nTokenTransferFrom(currencyId, msg.sender, from, to, amount); // Emit transfer events here so they come from the correct contract if (success) emit Transfer(from, to, amount); return success; } /// @notice Returns the present value of the nToken's assets denominated in asset tokens function getPresentValueAssetDenominated() external view returns (int256) { return proxy.nTokenPresentValueAssetDenominated(currencyId); } /// @notice Returns the present value of the nToken's assets denominated in underlying function getPresentValueUnderlyingDenominated() external view returns (int256) { return proxy.nTokenPresentValueUnderlyingDenominated(currencyId); } } // SPDX-License-Identifier: GPL-v3 pragma solidity >=0.7.0; /// @notice Used as a wrapper for tokens that are interest bearing for an /// underlying token. Follows the cToken interface, however, can be adapted /// for other interest bearing tokens. interface AssetRateAdapter { function token() external view returns (address); function decimals() external view returns (uint8); function description() external view returns (string memory); function version() external view returns (uint256); function underlying() external view returns (address); function getExchangeRateStateful() external returns (int256); function getExchangeRateView() external view returns (int256); function getAnnualizedSupplyRate() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0; import "./AggregatorInterface.sol"; import "./AggregatorV3Interface.sol"; interface AggregatorV2V3Interface is AggregatorInterface, AggregatorV3Interface { } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../../contracts/global/Types.sol"; import "interfaces/chainlink/AggregatorV2V3Interface.sol"; import "interfaces/notional/NotionalGovernance.sol"; interface NotionalGovernance { event ListCurrency(uint16 newCurrencyId); event UpdateETHRate(uint16 currencyId); event UpdateAssetRate(uint16 currencyId); event UpdateCashGroup(uint16 currencyId); event DeployNToken(uint16 currencyId, address nTokenAddress); event UpdateDepositParameters(uint16 currencyId); event UpdateInitializationParameters(uint16 currencyId); event UpdateIncentiveEmissionRate(uint16 currencyId, uint32 newEmissionRate); event UpdateTokenCollateralParameters(uint16 currencyId); event UpdateGlobalTransferOperator(address operator, bool approved); event UpdateAuthorizedCallbackContract(address operator, bool approved); event UpdateMaxCollateralBalance(uint16 currencyId, uint72 maxCollateralBalance); event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); event PauseRouterAndGuardianUpdated(address indexed pauseRouter, address indexed pauseGuardian); function transferOwnership(address newOwner) external; function setPauseRouterAndGuardian(address pauseRouter_, address pauseGuardian_) external; function listCurrency( TokenStorage calldata assetToken, TokenStorage calldata underlyingToken, AggregatorV2V3Interface rateOracle, bool mustInvert, uint8 buffer, uint8 haircut, uint8 liquidationDiscount ) external returns (uint16 currencyId); function updateMaxCollateralBalance( uint16 currencyId, uint72 maxCollateralBalanceInternalPrecision ) external; function enableCashGroup( uint16 currencyId, AssetRateAdapter assetRateOracle, CashGroupSettings calldata cashGroup, string calldata underlyingName, string calldata underlyingSymbol ) external; function updateDepositParameters( uint16 currencyId, uint32[] calldata depositShares, uint32[] calldata leverageThresholds ) external; function updateInitializationParameters( uint16 currencyId, uint32[] calldata annualizedAnchorRates, uint32[] calldata proportions ) external; function updateIncentiveEmissionRate(uint16 currencyId, uint32 newEmissionRate) external; function updateTokenCollateralParameters( uint16 currencyId, uint8 residualPurchaseIncentive10BPS, uint8 pvHaircutPercentage, uint8 residualPurchaseTimeBufferHours, uint8 cashWithholdingBuffer10BPS, uint8 liquidationHaircutPercentage ) external; function updateCashGroup(uint16 currencyId, CashGroupSettings calldata cashGroup) external; function updateAssetRate(uint16 currencyId, AssetRateAdapter rateOracle) external; function updateETHRate( uint16 currencyId, AggregatorV2V3Interface rateOracle, bool mustInvert, uint8 buffer, uint8 haircut, uint8 liquidationDiscount ) external; function updateGlobalTransferOperator(address operator, bool approved) external; function updateAuthorizedCallbackContract(address operator, bool approved) external; } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; interface nTokenERC20 { event Transfer(address indexed from, address indexed to, uint256 amount); event Approval(address indexed owner, address indexed spender, uint256 amount); function nTokenTotalSupply(address nTokenAddress) external view returns (uint256); function nTokenTransferAllowance( uint16 currencyId, address owner, address spender ) external view returns (uint256); function nTokenBalanceOf(uint16 currencyId, address account) external view returns (uint256); function nTokenTransferApprove( uint16 currencyId, address owner, address spender, uint256 amount ) external returns (bool); function nTokenTransfer( uint16 currencyId, address from, address to, uint256 amount ) external returns (bool); function nTokenTransferFrom( uint16 currencyId, address spender, address from, address to, uint256 amount ) external returns (bool); function nTokenTransferApproveAll(address spender, uint256 amount) external returns (bool); function nTokenClaimIncentives() external returns (uint256); function nTokenPresentValueAssetDenominated(uint16 currencyId) external view returns (int256); function nTokenPresentValueUnderlyingDenominated(uint16 currencyId) external view returns (int256); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; import "../global/Constants.sol"; library SafeInt256 { int256 private constant _INT256_MIN = type(int256).min; /// @dev Returns the multiplication of two signed integers, reverting on /// overflow. /// Counterpart to Solidity's `*` operator. /// Requirements: /// - Multiplication cannot overflow. function mul(int256 a, int256 b) internal pure returns (int256 c) { c = a * b; if (a == -1) require (b == 0 || c / b == a); else require (a == 0 || c / a == b); } /// @dev Returns the integer division of two signed integers. Reverts on /// division by zero. The result is rounded towards zero. /// Counterpart to Solidity's `/` operator. Note: this function uses a /// `revert` opcode (which leaves remaining gas untouched) while Solidity /// uses an invalid opcode to revert (consuming all remaining gas). /// Requirements: /// - The divisor cannot be zero. function div(int256 a, int256 b) internal pure returns (int256 c) { require(!(b == -1 && a == _INT256_MIN)); // dev: int256 div overflow // NOTE: solidity will automatically revert on divide by zero c = a / b; } function sub(int256 x, int256 y) internal pure returns (int256 z) { // taken from uniswap v3 require((z = x - y) <= x == (y >= 0)); } function add(int256 x, int256 y) internal pure returns (int256 z) { require((z = x + y) >= x == (y >= 0)); } function neg(int256 x) internal pure returns (int256 y) { return mul(-1, x); } function abs(int256 x) internal pure returns (int256) { if (x < 0) return neg(x); else return x; } function subNoNeg(int256 x, int256 y) internal pure returns (int256 z) { z = sub(x, y); require(z >= 0); // dev: int256 sub to negative return z; } /// @dev Calculates x * RATE_PRECISION / y while checking overflows function divInRatePrecision(int256 x, int256 y) internal pure returns (int256) { return div(mul(x, Constants.RATE_PRECISION), y); } /// @dev Calculates x * y / RATE_PRECISION while checking overflows function mulInRatePrecision(int256 x, int256 y) internal pure returns (int256) { return div(mul(x, y), Constants.RATE_PRECISION); } function toUint(int256 x) internal pure returns (uint256) { require(x >= 0); return uint256(x); } function toInt(uint256 x) internal pure returns (int256) { require (x <= uint256(type(int256).max)); // dev: toInt overflow return int256(x); } function max(int256 x, int256 y) internal pure returns (int256) { return x > y ? x : y; } function min(int256 x, int256 y) internal pure returns (int256) { return x < y ? x : y; } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; /// @title All shared constants for the Notional system should be declared here. library Constants { // Return code for cTokens that represents no error uint256 internal constant COMPOUND_RETURN_CODE_NO_ERROR = 0; uint8 internal constant CETH_DECIMAL_PLACES = 8; // Token precision used for all internal balances, TokenHandler library ensures that we // limit the dust amount caused by precision mismatches int256 internal constant INTERNAL_TOKEN_PRECISION = 1e8; // ETH will be initialized as the first currency uint256 internal constant ETH_CURRENCY_ID = 1; uint8 internal constant ETH_DECIMAL_PLACES = 18; int256 internal constant ETH_DECIMALS = 1e18; // Used to prevent overflow when converting decimal places to decimal precision values via // 10**decimalPlaces. This is a safe value for int256 and uint256 variables. We apply this // constraint when storing decimal places in governance. uint256 internal constant MAX_DECIMAL_PLACES = 36; // Address of the reserve account address internal constant RESERVE = address(0); // NOTE: this address is hardcoded in the library, must update this on deployment address constant NOTE_TOKEN_ADDRESS = 0xCFEAead4947f0705A14ec42aC3D44129E1Ef3eD5; // Most significant bit bytes32 internal constant MSB = 0x8000000000000000000000000000000000000000000000000000000000000000; // Basis for percentages int256 internal constant PERCENTAGE_DECIMALS = 100; // Max number of traded markets, also used as the maximum number of assets in a portfolio array uint256 internal constant MAX_TRADED_MARKET_INDEX = 7; // Max number of fCash assets in a bitmap, this is based on the gas costs of calculating free collateral // for a bitmap portfolio uint256 internal constant MAX_BITMAP_ASSETS = 20; uint256 internal constant FIVE_MINUTES = 300; // Internal date representations, note we use a 6/30/360 week/month/year convention here uint256 internal constant DAY = 86400; // We use six day weeks to ensure that all time references divide evenly uint256 internal constant WEEK = DAY * 6; uint256 internal constant MONTH = WEEK * 5; uint256 internal constant QUARTER = MONTH * 3; uint256 internal constant YEAR = QUARTER * 4; // These constants are used in DateTime.sol uint256 internal constant DAYS_IN_WEEK = 6; uint256 internal constant DAYS_IN_MONTH = 30; uint256 internal constant DAYS_IN_QUARTER = 90; // Offsets for each time chunk denominated in days uint256 internal constant MAX_DAY_OFFSET = 90; uint256 internal constant MAX_WEEK_OFFSET = 360; uint256 internal constant MAX_MONTH_OFFSET = 2160; uint256 internal constant MAX_QUARTER_OFFSET = 7650; // Offsets for each time chunk denominated in bits uint256 internal constant WEEK_BIT_OFFSET = 90; uint256 internal constant MONTH_BIT_OFFSET = 135; uint256 internal constant QUARTER_BIT_OFFSET = 195; // This is a constant that represents the time period that all rates are normalized by, 360 days uint256 internal constant IMPLIED_RATE_TIME = 360 * DAY; // Number of decimal places that rates are stored in, equals 100% int256 internal constant RATE_PRECISION = 1e9; // One basis point in RATE_PRECISION terms uint256 internal constant BASIS_POINT = uint256(RATE_PRECISION / 10000); // Used to when calculating the amount to deleverage of a market when minting nTokens uint256 internal constant DELEVERAGE_BUFFER = 300 * BASIS_POINT; // Used for scaling cash group factors uint256 internal constant FIVE_BASIS_POINTS = 5 * BASIS_POINT; // Used for residual purchase incentive and cash withholding buffer uint256 internal constant TEN_BASIS_POINTS = 10 * BASIS_POINT; // This is the ABDK64x64 representation of RATE_PRECISION // RATE_PRECISION_64x64 = ABDKMath64x64.fromUint(RATE_PRECISION) int128 internal constant RATE_PRECISION_64x64 = 0x3b9aca000000000000000000; int128 internal constant LOG_RATE_PRECISION_64x64 = 382276781265598821176; // Limit the market proportion so that borrowing cannot hit extremely high interest rates int256 internal constant MAX_MARKET_PROPORTION = RATE_PRECISION * 96 / 100; uint8 internal constant FCASH_ASSET_TYPE = 1; // Liquidity token asset types are 1 + marketIndex (where marketIndex is 1-indexed) uint8 internal constant MIN_LIQUIDITY_TOKEN_INDEX = 2; uint8 internal constant MAX_LIQUIDITY_TOKEN_INDEX = 8; // Used for converting bool to bytes1, solidity does not have a native conversion // method for this bytes1 internal constant BOOL_FALSE = 0x00; bytes1 internal constant BOOL_TRUE = 0x01; // Account context flags bytes1 internal constant HAS_ASSET_DEBT = 0x01; bytes1 internal constant HAS_CASH_DEBT = 0x02; bytes2 internal constant ACTIVE_IN_PORTFOLIO = 0x8000; bytes2 internal constant ACTIVE_IN_BALANCES = 0x4000; bytes2 internal constant UNMASK_FLAGS = 0x3FFF; uint16 internal constant MAX_CURRENCIES = uint16(UNMASK_FLAGS); // Equal to 100% of all deposit amounts for nToken liquidity across fCash markets. int256 internal constant DEPOSIT_PERCENT_BASIS = 1e8; // nToken Parameters: there are offsets in the nTokenParameters bytes6 variable returned // in nTokenHandler. Each constant represents a position in the byte array. uint8 internal constant LIQUIDATION_HAIRCUT_PERCENTAGE = 0; uint8 internal constant CASH_WITHHOLDING_BUFFER = 1; uint8 internal constant RESIDUAL_PURCHASE_TIME_BUFFER = 2; uint8 internal constant PV_HAIRCUT_PERCENTAGE = 3; uint8 internal constant RESIDUAL_PURCHASE_INCENTIVE = 4; // Liquidation parameters // Default percentage of collateral that a liquidator is allowed to liquidate, will be higher if the account // requires more collateral to be liquidated int256 internal constant DEFAULT_LIQUIDATION_PORTION = 40; // Percentage of local liquidity token cash claim delivered to the liquidator for liquidating liquidity tokens int256 internal constant TOKEN_REPO_INCENTIVE_PERCENT = 30; // Pause Router liquidation enabled states bytes1 internal constant LOCAL_CURRENCY_ENABLED = 0x01; bytes1 internal constant COLLATERAL_CURRENCY_ENABLED = 0x02; bytes1 internal constant LOCAL_FCASH_ENABLED = 0x04; bytes1 internal constant CROSS_CURRENCY_FCASH_ENABLED = 0x08; } // SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.7.0; import "./CTokenInterface.sol"; interface CErc20Interface { /*** User Interface ***/ function mint(uint mintAmount) external returns (uint); function redeem(uint redeemTokens) external returns (uint); function redeemUnderlying(uint redeemAmount) external returns (uint); function borrow(uint borrowAmount) external returns (uint); function repayBorrow(uint repayAmount) external returns (uint); function repayBorrowBehalf(address borrower, uint repayAmount) external returns (uint); function liquidateBorrow(address borrower, uint repayAmount, CTokenInterface cTokenCollateral) external returns (uint); } // SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.7.0; interface CEtherInterface { function mint() external payable; } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; /** * @title EIP20NonStandardInterface * @dev Version of ERC20 with no return values for `transfer` and `transferFrom` * See https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */ interface IEIP20NonStandard { /** * @notice Get the total number of tokens in circulation * @return The supply of tokens */ function totalSupply() external view returns (uint256); /** * @notice Gets the balance of the specified address * @param owner The address from which the balance will be retrieved * @return balance */ function balanceOf(address owner) external view returns (uint256 balance); /// /// !!!!!!!!!!!!!! /// !!! NOTICE !!! `transfer` does not return a value, in violation of the ERC-20 specification /// !!!!!!!!!!!!!! /// /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer */ function transfer(address dst, uint256 amount) external; /// /// !!!!!!!!!!!!!! /// !!! NOTICE !!! `transferFrom` does not return a value, in violation of the ERC-20 specification /// !!!!!!!!!!!!!! /// /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer */ function transferFrom(address src, address dst, uint256 amount) external; /// /// !!!!!!!!!!!!!! /// !!! NOTICE !!! `approve` does not return a value, in violation of the ERC-20 specification /// !!!!!!!!!!!!!! /// /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved */ function approve(address spender, uint256 amount) external; /** * @notice Get the current allowance from `owner` for `spender` * @param owner The address of the account which owns the tokens to be spent * @param spender The address of the account which may transfer tokens * @return remaining The number of tokens allowed to be spent */ function allowance(address owner, address spender) external view returns (uint256 remaining); event Transfer(address indexed from, address indexed to, uint256 amount); event Approval(address indexed owner, address indexed spender, uint256 amount); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal virtual { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0; 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); event AnswerUpdated(int256 indexed current, uint256 indexed roundId, uint256 updatedAt); event NewRound(uint256 indexed roundId, address indexed startedBy, uint256 startedAt); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0; interface AggregatorV3Interface { function decimals() external view returns (uint8); function description() external view returns (string memory); function version() external view returns (uint256); // getRoundData and latestRoundData should both raise "No data present" // if they do not have data to report, instead of returning unset values // which could be misinterpreted as actual reported values. function getRoundData(uint80 _roundId) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function latestRoundData() external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); } // SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.7.0; interface CTokenInterface { /*** User Interface ***/ function underlying() external view returns (address); function transfer(address dst, uint amount) external returns (bool); function transferFrom(address src, address dst, uint amount) external returns (bool); function approve(address spender, uint amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint); function balanceOf(address owner) external view returns (uint); function balanceOfUnderlying(address owner) external returns (uint); function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint); function borrowRatePerBlock() external view returns (uint); function supplyRatePerBlock() external view returns (uint); function totalBorrowsCurrent() external returns (uint); function borrowBalanceCurrent(address account) external returns (uint); function borrowBalanceStored(address account) external view returns (uint); function exchangeRateCurrent() external returns (uint); function exchangeRateStored() external view returns (uint); function getCash() external view returns (uint); function accrueInterest() external returns (uint); function seize(address liquidator, address borrower, uint seizeTokens) external returns (uint); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "./AssetRate.sol"; import "./CashGroup.sol"; import "./DateTime.sol"; import "../balances/BalanceHandler.sol"; import "../../global/LibStorage.sol"; import "../../global/Types.sol"; import "../../global/Constants.sol"; import "../../math/SafeInt256.sol"; import "../../math/ABDKMath64x64.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; library Market { using SafeMath for uint256; using SafeInt256 for int256; using CashGroup for CashGroupParameters; using AssetRate for AssetRateParameters; // Max positive value for a ABDK64x64 integer int256 private constant MAX64 = 0x7FFFFFFFFFFFFFFF; /// @notice Add liquidity to a market, assuming that it is initialized. If not then /// this method will revert and the market must be initialized first. /// Return liquidityTokens and negative fCash to the portfolio function addLiquidity(MarketParameters memory market, int256 assetCash) internal returns (int256 liquidityTokens, int256 fCash) { require(market.totalLiquidity > 0, "M: zero liquidity"); if (assetCash == 0) return (0, 0); require(assetCash > 0); // dev: negative asset cash liquidityTokens = market.totalLiquidity.mul(assetCash).div(market.totalAssetCash); // No need to convert this to underlying, assetCash / totalAssetCash is a unitless proportion. fCash = market.totalfCash.mul(assetCash).div(market.totalAssetCash); market.totalLiquidity = market.totalLiquidity.add(liquidityTokens); market.totalfCash = market.totalfCash.add(fCash); market.totalAssetCash = market.totalAssetCash.add(assetCash); _setMarketStorageForLiquidity(market); // Flip the sign to represent the LP's net position fCash = fCash.neg(); } /// @notice Remove liquidity from a market, assuming that it is initialized. /// Return assetCash and positive fCash to the portfolio function removeLiquidity(MarketParameters memory market, int256 tokensToRemove) internal returns (int256 assetCash, int256 fCash) { if (tokensToRemove == 0) return (0, 0); require(tokensToRemove > 0); // dev: negative tokens to remove assetCash = market.totalAssetCash.mul(tokensToRemove).div(market.totalLiquidity); fCash = market.totalfCash.mul(tokensToRemove).div(market.totalLiquidity); market.totalLiquidity = market.totalLiquidity.subNoNeg(tokensToRemove); market.totalfCash = market.totalfCash.subNoNeg(fCash); market.totalAssetCash = market.totalAssetCash.subNoNeg(assetCash); _setMarketStorageForLiquidity(market); } function executeTrade( MarketParameters memory market, CashGroupParameters memory cashGroup, int256 fCashToAccount, uint256 timeToMaturity, uint256 marketIndex ) internal returns (int256 netAssetCash) { int256 netAssetCashToReserve; (netAssetCash, netAssetCashToReserve) = calculateTrade( market, cashGroup, fCashToAccount, timeToMaturity, marketIndex ); MarketStorage storage marketStorage = _getMarketStoragePointer(market); _setMarketStorage( marketStorage, market.totalfCash, market.totalAssetCash, market.lastImpliedRate, market.oracleRate, market.previousTradeTime ); BalanceHandler.incrementFeeToReserve(cashGroup.currencyId, netAssetCashToReserve); } /// @notice Calculates the asset cash amount the results from trading fCashToAccount with the market. A positive /// fCashToAccount is equivalent of lending, a negative is borrowing. Updates the market state in memory. /// @param market the current market state /// @param cashGroup cash group configuration parameters /// @param fCashToAccount the fCash amount that will be deposited into the user's portfolio. The net change /// to the market is in the opposite direction. /// @param timeToMaturity number of seconds until maturity /// @return netAssetCash, netAssetCashToReserve function calculateTrade( MarketParameters memory market, CashGroupParameters memory cashGroup, int256 fCashToAccount, uint256 timeToMaturity, uint256 marketIndex ) internal view returns (int256, int256) { // We return false if there is not enough fCash to support this trade. // if fCashToAccount > 0 and totalfCash - fCashToAccount <= 0 then the trade will fail // if fCashToAccount < 0 and totalfCash > 0 then this will always pass if (market.totalfCash <= fCashToAccount) return (0, 0); // Calculates initial rate factors for the trade (int256 rateScalar, int256 totalCashUnderlying, int256 rateAnchor) = getExchangeRateFactors(market, cashGroup, timeToMaturity, marketIndex); // Calculates the exchange rate from cash to fCash before any liquidity fees // are applied int256 preFeeExchangeRate; { bool success; (preFeeExchangeRate, success) = _getExchangeRate( market.totalfCash, totalCashUnderlying, rateScalar, rateAnchor, fCashToAccount ); if (!success) return (0, 0); } // Given the exchange rate, returns the net cash amounts to apply to each of the // three relevant balances. (int256 netCashToAccount, int256 netCashToMarket, int256 netCashToReserve) = _getNetCashAmountsUnderlying( cashGroup, preFeeExchangeRate, fCashToAccount, timeToMaturity ); // Signifies a failed net cash amount calculation if (netCashToAccount == 0) return (0, 0); { // Set the new implied interest rate after the trade has taken effect, this // will be used to calculate the next trader's interest rate. market.totalfCash = market.totalfCash.subNoNeg(fCashToAccount); market.lastImpliedRate = getImpliedRate( market.totalfCash, totalCashUnderlying.add(netCashToMarket), rateScalar, rateAnchor, timeToMaturity ); // It's technically possible that the implied rate is actually exactly zero (or // more accurately the natural log rounds down to zero) but we will still fail // in this case. If this does happen we may assume that markets are not initialized. if (market.lastImpliedRate == 0) return (0, 0); } return _setNewMarketState( market, cashGroup.assetRate, netCashToAccount, netCashToMarket, netCashToReserve ); } /// @notice Returns factors for calculating exchange rates /// @return /// rateScalar: a scalar value in rate precision that defines the slope of the line /// totalCashUnderlying: the converted asset cash to underlying cash for calculating /// the exchange rates for the trade /// rateAnchor: an offset from the x axis to maintain interest rate continuity over time function getExchangeRateFactors( MarketParameters memory market, CashGroupParameters memory cashGroup, uint256 timeToMaturity, uint256 marketIndex ) internal pure returns ( int256, int256, int256 ) { int256 rateScalar = cashGroup.getRateScalar(marketIndex, timeToMaturity); int256 totalCashUnderlying = cashGroup.assetRate.convertToUnderlying(market.totalAssetCash); // This would result in a divide by zero if (market.totalfCash == 0 || totalCashUnderlying == 0) return (0, 0, 0); // Get the rate anchor given the market state, this will establish the baseline for where // the exchange rate is set. int256 rateAnchor; { bool success; (rateAnchor, success) = _getRateAnchor( market.totalfCash, market.lastImpliedRate, totalCashUnderlying, rateScalar, timeToMaturity ); if (!success) return (0, 0, 0); } return (rateScalar, totalCashUnderlying, rateAnchor); } /// @dev Returns net asset cash amounts to the account, the market and the reserve /// @return /// netCashToAccount: this is a positive or negative amount of cash change to the account /// netCashToMarket: this is a positive or negative amount of cash change in the market // netCashToReserve: this is always a positive amount of cash accrued to the reserve function _getNetCashAmountsUnderlying( CashGroupParameters memory cashGroup, int256 preFeeExchangeRate, int256 fCashToAccount, uint256 timeToMaturity ) private pure returns ( int256, int256, int256 ) { // Fees are specified in basis points which is an rate precision denomination. We convert this to // an exchange rate denomination for the given time to maturity. (i.e. get e^(fee * t) and multiply // or divide depending on the side of the trade). // tradeExchangeRate = exp((tradeInterestRateNoFee +/- fee) * timeToMaturity) // tradeExchangeRate = tradeExchangeRateNoFee (* or /) exp(fee * timeToMaturity) // cash = fCash / exchangeRate, exchangeRate > 1 int256 preFeeCashToAccount = fCashToAccount.divInRatePrecision(preFeeExchangeRate).neg(); int256 fee = getExchangeRateFromImpliedRate(cashGroup.getTotalFee(), timeToMaturity); if (fCashToAccount > 0) { // Lending // Dividing reduces exchange rate, lending should receive less fCash for cash int256 postFeeExchangeRate = preFeeExchangeRate.divInRatePrecision(fee); // It's possible that the fee pushes exchange rates into negative territory. This is not possible // when borrowing. If this happens then the trade has failed. if (postFeeExchangeRate < Constants.RATE_PRECISION) return (0, 0, 0); // cashToAccount = -(fCashToAccount / exchangeRate) // postFeeExchangeRate = preFeeExchangeRate / feeExchangeRate // preFeeCashToAccount = -(fCashToAccount / preFeeExchangeRate) // postFeeCashToAccount = -(fCashToAccount / postFeeExchangeRate) // netFee = preFeeCashToAccount - postFeeCashToAccount // netFee = (fCashToAccount / postFeeExchangeRate) - (fCashToAccount / preFeeExchangeRate) // netFee = ((fCashToAccount * feeExchangeRate) / preFeeExchangeRate) - (fCashToAccount / preFeeExchangeRate) // netFee = (fCashToAccount / preFeeExchangeRate) * (feeExchangeRate - 1) // netFee = -(preFeeCashToAccount) * (feeExchangeRate - 1) // netFee = preFeeCashToAccount * (1 - feeExchangeRate) // RATE_PRECISION - fee will be negative here, preFeeCashToAccount < 0, fee > 0 fee = preFeeCashToAccount.mulInRatePrecision(Constants.RATE_PRECISION.sub(fee)); } else { // Borrowing // cashToAccount = -(fCashToAccount / exchangeRate) // postFeeExchangeRate = preFeeExchangeRate * feeExchangeRate // netFee = preFeeCashToAccount - postFeeCashToAccount // netFee = (fCashToAccount / postFeeExchangeRate) - (fCashToAccount / preFeeExchangeRate) // netFee = ((fCashToAccount / (feeExchangeRate * preFeeExchangeRate)) - (fCashToAccount / preFeeExchangeRate) // netFee = (fCashToAccount / preFeeExchangeRate) * (1 / feeExchangeRate - 1) // netFee = preFeeCashToAccount * ((1 - feeExchangeRate) / feeExchangeRate) // NOTE: preFeeCashToAccount is negative in this branch so we negate it to ensure that fee is a positive number // preFee * (1 - fee) / fee will be negative, use neg() to flip to positive // RATE_PRECISION - fee will be negative fee = preFeeCashToAccount.mul(Constants.RATE_PRECISION.sub(fee)).div(fee).neg(); } int256 cashToReserve = fee.mul(cashGroup.getReserveFeeShare()).div(Constants.PERCENTAGE_DECIMALS); return ( // postFeeCashToAccount = preFeeCashToAccount - fee preFeeCashToAccount.sub(fee), // netCashToMarket = -(preFeeCashToAccount - fee + cashToReserve) (preFeeCashToAccount.sub(fee).add(cashToReserve)).neg(), cashToReserve ); } /// @notice Sets the new market state /// @return /// netAssetCashToAccount: the positive or negative change in asset cash to the account /// assetCashToReserve: the positive amount of cash that accrues to the reserve function _setNewMarketState( MarketParameters memory market, AssetRateParameters memory assetRate, int256 netCashToAccount, int256 netCashToMarket, int256 netCashToReserve ) private view returns (int256, int256) { int256 netAssetCashToMarket = assetRate.convertFromUnderlying(netCashToMarket); // Set storage checks that total asset cash is above zero market.totalAssetCash = market.totalAssetCash.add(netAssetCashToMarket); // Sets the trade time for the next oracle update market.previousTradeTime = block.timestamp; int256 assetCashToReserve = assetRate.convertFromUnderlying(netCashToReserve); int256 netAssetCashToAccount = assetRate.convertFromUnderlying(netCashToAccount); return (netAssetCashToAccount, assetCashToReserve); } /// @notice Rate anchors update as the market gets closer to maturity. Rate anchors are not comparable /// across time or markets but implied rates are. The goal here is to ensure that the implied rate /// before and after the rate anchor update is the same. Therefore, the market will trade at the same implied /// rate that it last traded at. If these anchors do not update then it opens up the opportunity for arbitrage /// which will hurt the liquidity providers. /// /// The rate anchor will update as the market rolls down to maturity. The calculation is: /// newExchangeRate = e^(lastImpliedRate * timeToMaturity / Constants.IMPLIED_RATE_TIME) /// newAnchor = newExchangeRate - ln((proportion / (1 - proportion)) / rateScalar /// /// where: /// lastImpliedRate = ln(exchangeRate') * (Constants.IMPLIED_RATE_TIME / timeToMaturity') /// (calculated when the last trade in the market was made) /// @return the new rate anchor and a boolean that signifies success function _getRateAnchor( int256 totalfCash, uint256 lastImpliedRate, int256 totalCashUnderlying, int256 rateScalar, uint256 timeToMaturity ) internal pure returns (int256, bool) { // This is the exchange rate at the new time to maturity int256 newExchangeRate = getExchangeRateFromImpliedRate(lastImpliedRate, timeToMaturity); if (newExchangeRate < Constants.RATE_PRECISION) return (0, false); int256 rateAnchor; { // totalfCash / (totalfCash + totalCashUnderlying) int256 proportion = totalfCash.divInRatePrecision(totalfCash.add(totalCashUnderlying)); (int256 lnProportion, bool success) = _logProportion(proportion); if (!success) return (0, false); // newExchangeRate - ln(proportion / (1 - proportion)) / rateScalar rateAnchor = newExchangeRate.sub(lnProportion.divInRatePrecision(rateScalar)); } return (rateAnchor, true); } /// @notice Calculates the current market implied rate. /// @return the implied rate and a bool that is true on success function getImpliedRate( int256 totalfCash, int256 totalCashUnderlying, int256 rateScalar, int256 rateAnchor, uint256 timeToMaturity ) internal pure returns (uint256) { // This will check for exchange rates < Constants.RATE_PRECISION (int256 exchangeRate, bool success) = _getExchangeRate(totalfCash, totalCashUnderlying, rateScalar, rateAnchor, 0); if (!success) return 0; // Uses continuous compounding to calculate the implied rate: // ln(exchangeRate) * Constants.IMPLIED_RATE_TIME / timeToMaturity int128 rate = ABDKMath64x64.fromInt(exchangeRate); // Scales down to a floating point for LN int128 rateScaled = ABDKMath64x64.div(rate, Constants.RATE_PRECISION_64x64); // We will not have a negative log here because we check that exchangeRate > Constants.RATE_PRECISION // inside getExchangeRate int128 lnRateScaled = ABDKMath64x64.ln(rateScaled); // Scales up to a fixed point uint256 lnRate = ABDKMath64x64.toUInt(ABDKMath64x64.mul(lnRateScaled, Constants.RATE_PRECISION_64x64)); // lnRate * IMPLIED_RATE_TIME / ttm uint256 impliedRate = lnRate.mul(Constants.IMPLIED_RATE_TIME).div(timeToMaturity); // Implied rates over 429% will overflow, this seems like a safe assumption if (impliedRate > type(uint32).max) return 0; return impliedRate; } /// @notice Converts an implied rate to an exchange rate given a time to maturity. The /// formula is E = e^rt function getExchangeRateFromImpliedRate(uint256 impliedRate, uint256 timeToMaturity) internal pure returns (int256) { int128 expValue = ABDKMath64x64.fromUInt( impliedRate.mul(timeToMaturity).div(Constants.IMPLIED_RATE_TIME) ); int128 expValueScaled = ABDKMath64x64.div(expValue, Constants.RATE_PRECISION_64x64); int128 expResult = ABDKMath64x64.exp(expValueScaled); int128 expResultScaled = ABDKMath64x64.mul(expResult, Constants.RATE_PRECISION_64x64); return ABDKMath64x64.toInt(expResultScaled); } /// @notice Returns the exchange rate between fCash and cash for the given market /// Calculates the following exchange rate: /// (1 / rateScalar) * ln(proportion / (1 - proportion)) + rateAnchor /// where: /// proportion = totalfCash / (totalfCash + totalUnderlyingCash) /// @dev has an underscore to denote as private but is marked internal for the mock function _getExchangeRate( int256 totalfCash, int256 totalCashUnderlying, int256 rateScalar, int256 rateAnchor, int256 fCashToAccount ) internal pure returns (int256, bool) { int256 numerator = totalfCash.subNoNeg(fCashToAccount); // This is the proportion scaled by Constants.RATE_PRECISION // (totalfCash + fCash) / (totalfCash + totalCashUnderlying) int256 proportion = numerator.divInRatePrecision(totalfCash.add(totalCashUnderlying)); // This limit is here to prevent the market from reaching extremely high interest rates via an // excessively large proportion (high amounts of fCash relative to cash). // Market proportion can only increase via borrowing (fCash is added to the market and cash is // removed). Over time, the returns from asset cash will slightly decrease the proportion (the // value of cash underlying in the market must be monotonically increasing). Therefore it is not // possible for the proportion to go over max market proportion unless borrowing occurs. if (proportion > Constants.MAX_MARKET_PROPORTION) return (0, false); (int256 lnProportion, bool success) = _logProportion(proportion); if (!success) return (0, false); // lnProportion / rateScalar + rateAnchor int256 rate = lnProportion.divInRatePrecision(rateScalar).add(rateAnchor); // Do not succeed if interest rates fall below 1 if (rate < Constants.RATE_PRECISION) { return (0, false); } else { return (rate, true); } } /// @dev This method calculates the log of the proportion inside the logit function which is /// defined as ln(proportion / (1 - proportion)). Special handling here is required to deal with /// fixed point precision and the ABDK library. function _logProportion(int256 proportion) internal pure returns (int256, bool) { // This will result in divide by zero, short circuit if (proportion == Constants.RATE_PRECISION) return (0, false); // Convert proportion to what is used inside the logit function (p / (1-p)) int256 logitP = proportion.divInRatePrecision(Constants.RATE_PRECISION.sub(proportion)); // ABDK does not handle log of numbers that are less than 1, in order to get the right value // scaled by RATE_PRECISION we use the log identity: // (ln(logitP / RATE_PRECISION)) * RATE_PRECISION = (ln(logitP) - ln(RATE_PRECISION)) * RATE_PRECISION int128 abdkProportion = ABDKMath64x64.fromInt(logitP); // Here, abdk will revert due to negative log so abort if (abdkProportion <= 0) return (0, false); int256 result = ABDKMath64x64.toInt( ABDKMath64x64.mul( ABDKMath64x64.sub( ABDKMath64x64.ln(abdkProportion), Constants.LOG_RATE_PRECISION_64x64 ), Constants.RATE_PRECISION_64x64 ) ); return (result, true); } /// @notice Oracle rate protects against short term price manipulation. Time window will be set to a value /// on the order of minutes to hours. This is to protect fCash valuations from market manipulation. For example, /// a trader could use a flash loan to dump a large amount of cash into the market and depress interest rates. /// Since we value fCash in portfolios based on these rates, portfolio values will decrease and they may then /// be liquidated. /// /// Oracle rates are calculated when the market is loaded from storage. /// /// The oracle rate is a lagged weighted average over a short term price window. If we are past /// the short term window then we just set the rate to the lastImpliedRate, otherwise we take the /// weighted average: /// lastImpliedRatePreTrade * (currentTs - previousTs) / timeWindow + /// oracleRatePrevious * (1 - (currentTs - previousTs) / timeWindow) function _updateRateOracle( uint256 previousTradeTime, uint256 lastImpliedRate, uint256 oracleRate, uint256 rateOracleTimeWindow, uint256 blockTime ) private pure returns (uint256) { require(rateOracleTimeWindow > 0); // dev: update rate oracle, time window zero // This can occur when using a view function get to a market state in the past if (previousTradeTime > blockTime) return lastImpliedRate; uint256 timeDiff = blockTime.sub(previousTradeTime); if (timeDiff > rateOracleTimeWindow) { // If past the time window just return the lastImpliedRate return lastImpliedRate; } // (currentTs - previousTs) / timeWindow uint256 lastTradeWeight = timeDiff.mul(uint256(Constants.RATE_PRECISION)).div(rateOracleTimeWindow); // 1 - (currentTs - previousTs) / timeWindow uint256 oracleWeight = uint256(Constants.RATE_PRECISION).sub(lastTradeWeight); uint256 newOracleRate = (lastImpliedRate.mul(lastTradeWeight).add(oracleRate.mul(oracleWeight))).div( uint256(Constants.RATE_PRECISION) ); return newOracleRate; } function getOracleRate( uint256 currencyId, uint256 maturity, uint256 rateOracleTimeWindow, uint256 blockTime ) internal view returns (uint256) { mapping(uint256 => mapping(uint256 => mapping(uint256 => MarketStorage))) storage store = LibStorage.getMarketStorage(); uint256 settlementDate = DateTime.getReferenceTime(blockTime) + Constants.QUARTER; MarketStorage storage marketStorage = store[currencyId][maturity][settlementDate]; uint256 lastImpliedRate = marketStorage.lastImpliedRate; uint256 oracleRate = marketStorage.oracleRate; uint256 previousTradeTime = marketStorage.previousTradeTime; // If the oracle rate is set to zero this can only be because the markets have past their settlement // date but the new set of markets has not yet been initialized. This means that accounts cannot be liquidated // during this time, but market initialization can be called by anyone so the actual time that this condition // exists for should be quite short. require(oracleRate > 0, "Market not initialized"); return _updateRateOracle( previousTradeTime, lastImpliedRate, oracleRate, rateOracleTimeWindow, blockTime ); } /// @notice Reads a market object directly from storage. `buildMarket` should be called instead of this method /// which ensures that the rate oracle is set properly. function _loadMarketStorage( MarketParameters memory market, uint256 currencyId, uint256 maturity, bool needsLiquidity, uint256 settlementDate ) private view { // Market object always uses the most current reference time as the settlement date mapping(uint256 => mapping(uint256 => mapping(uint256 => MarketStorage))) storage store = LibStorage.getMarketStorage(); MarketStorage storage marketStorage = store[currencyId][maturity][settlementDate]; bytes32 slot; assembly { slot := marketStorage.slot } market.storageSlot = slot; market.maturity = maturity; market.totalfCash = marketStorage.totalfCash; market.totalAssetCash = marketStorage.totalAssetCash; market.lastImpliedRate = marketStorage.lastImpliedRate; market.oracleRate = marketStorage.oracleRate; market.previousTradeTime = marketStorage.previousTradeTime; if (needsLiquidity) { market.totalLiquidity = marketStorage.totalLiquidity; } else { market.totalLiquidity = 0; } } function _getMarketStoragePointer( MarketParameters memory market ) private pure returns (MarketStorage storage marketStorage) { bytes32 slot = market.storageSlot; assembly { marketStorage.slot := slot } } function _setMarketStorageForLiquidity(MarketParameters memory market) internal { MarketStorage storage marketStorage = _getMarketStoragePointer(market); // Oracle rate does not change on liquidity uint32 storedOracleRate = marketStorage.oracleRate; _setMarketStorage( marketStorage, market.totalfCash, market.totalAssetCash, market.lastImpliedRate, storedOracleRate, market.previousTradeTime ); _setTotalLiquidity(marketStorage, market.totalLiquidity); } function setMarketStorageForInitialize( MarketParameters memory market, uint256 currencyId, uint256 settlementDate ) internal { // On initialization we have not yet calculated the storage slot so we get it here. mapping(uint256 => mapping(uint256 => mapping(uint256 => MarketStorage))) storage store = LibStorage.getMarketStorage(); MarketStorage storage marketStorage = store[currencyId][market.maturity][settlementDate]; _setMarketStorage( marketStorage, market.totalfCash, market.totalAssetCash, market.lastImpliedRate, market.oracleRate, market.previousTradeTime ); _setTotalLiquidity(marketStorage, market.totalLiquidity); } function _setTotalLiquidity( MarketStorage storage marketStorage, int256 totalLiquidity ) internal { require(totalLiquidity >= 0 && totalLiquidity <= type(uint80).max); // dev: market storage totalLiquidity overflow marketStorage.totalLiquidity = uint80(totalLiquidity); } function _setMarketStorage( MarketStorage storage marketStorage, int256 totalfCash, int256 totalAssetCash, uint256 lastImpliedRate, uint256 oracleRate, uint256 previousTradeTime ) private { require(totalfCash >= 0 && totalfCash <= type(uint80).max); // dev: storage totalfCash overflow require(totalAssetCash >= 0 && totalAssetCash <= type(uint80).max); // dev: storage totalAssetCash overflow require(0 < lastImpliedRate && lastImpliedRate <= type(uint32).max); // dev: storage lastImpliedRate overflow require(0 < oracleRate && oracleRate <= type(uint32).max); // dev: storage oracleRate overflow require(0 <= previousTradeTime && previousTradeTime <= type(uint32).max); // dev: storage previous trade time overflow marketStorage.totalfCash = uint80(totalfCash); marketStorage.totalAssetCash = uint80(totalAssetCash); marketStorage.lastImpliedRate = uint32(lastImpliedRate); marketStorage.oracleRate = uint32(oracleRate); marketStorage.previousTradeTime = uint32(previousTradeTime); } /// @notice Creates a market object and ensures that the rate oracle time window is updated appropriately. function loadMarket( MarketParameters memory market, uint256 currencyId, uint256 maturity, uint256 blockTime, bool needsLiquidity, uint256 rateOracleTimeWindow ) internal view { // Always reference the current settlement date uint256 settlementDate = DateTime.getReferenceTime(blockTime) + Constants.QUARTER; loadMarketWithSettlementDate( market, currencyId, maturity, blockTime, needsLiquidity, rateOracleTimeWindow, settlementDate ); } /// @notice Creates a market object and ensures that the rate oracle time window is updated appropriately, this /// is mainly used in the InitializeMarketAction contract. function loadMarketWithSettlementDate( MarketParameters memory market, uint256 currencyId, uint256 maturity, uint256 blockTime, bool needsLiquidity, uint256 rateOracleTimeWindow, uint256 settlementDate ) internal view { _loadMarketStorage(market, currencyId, maturity, needsLiquidity, settlementDate); market.oracleRate = _updateRateOracle( market.previousTradeTime, market.lastImpliedRate, market.oracleRate, rateOracleTimeWindow, blockTime ); } function loadSettlementMarket( MarketParameters memory market, uint256 currencyId, uint256 maturity, uint256 settlementDate ) internal view { _loadMarketStorage(market, currencyId, maturity, true, settlementDate); } /// Uses Newton's method to converge on an fCash amount given the amount of /// cash. The relation between cash and fcash is: /// cashAmount * exchangeRate * fee + fCash = 0 /// where exchangeRate(fCash) = (rateScalar ^ -1) * ln(p / (1 - p)) + rateAnchor /// p = (totalfCash - fCash) / (totalfCash + totalCash) /// if cashAmount < 0: fee = feeRate ^ -1 /// if cashAmount > 0: fee = feeRate /// /// Newton's method is: /// fCash_(n+1) = fCash_n - f(fCash) / f'(fCash) /// /// f(fCash) = cashAmount * exchangeRate(fCash) * fee + fCash /// /// (totalfCash + totalCash) /// exchangeRate'(fCash) = - ------------------------------------------ /// (totalfCash - fCash) * (totalCash + fCash) /// /// https://www.wolframalpha.com/input/?i=ln%28%28%28a-x%29%2F%28a%2Bb%29%29%2F%281-%28a-x%29%2F%28a%2Bb%29%29%29 /// /// (cashAmount * fee) * (totalfCash + totalCash) /// f'(fCash) = 1 - ------------------------------------------------------ /// rateScalar * (totalfCash - fCash) * (totalCash + fCash) /// /// NOTE: each iteration costs about 11.3k so this is only done via a view function. function getfCashGivenCashAmount( int256 totalfCash, int256 netCashToAccount, int256 totalCashUnderlying, int256 rateScalar, int256 rateAnchor, int256 feeRate, int256 maxDelta ) internal pure returns (int256) { require(maxDelta >= 0); int256 fCashChangeToAccountGuess = netCashToAccount.mulInRatePrecision(rateAnchor).neg(); for (uint8 i = 0; i < 250; i++) { (int256 exchangeRate, bool success) = _getExchangeRate( totalfCash, totalCashUnderlying, rateScalar, rateAnchor, fCashChangeToAccountGuess ); require(success); // dev: invalid exchange rate int256 delta = _calculateDelta( netCashToAccount, totalfCash, totalCashUnderlying, rateScalar, fCashChangeToAccountGuess, exchangeRate, feeRate ); if (delta.abs() <= maxDelta) return fCashChangeToAccountGuess; fCashChangeToAccountGuess = fCashChangeToAccountGuess.sub(delta); } revert("No convergence"); } /// @dev Calculates: f(fCash) / f'(fCash) /// f(fCash) = cashAmount * exchangeRate * fee + fCash /// (cashAmount * fee) * (totalfCash + totalCash) /// f'(fCash) = 1 - ------------------------------------------------------ /// rateScalar * (totalfCash - fCash) * (totalCash + fCash) function _calculateDelta( int256 cashAmount, int256 totalfCash, int256 totalCashUnderlying, int256 rateScalar, int256 fCashGuess, int256 exchangeRate, int256 feeRate ) private pure returns (int256) { int256 derivative; // rateScalar * (totalfCash - fCash) * (totalCash + fCash) // Precision: TOKEN_PRECISION ^ 2 int256 denominator = rateScalar.mulInRatePrecision( (totalfCash.sub(fCashGuess)).mul(totalCashUnderlying.add(fCashGuess)) ); if (fCashGuess > 0) { // Lending exchangeRate = exchangeRate.divInRatePrecision(feeRate); require(exchangeRate >= Constants.RATE_PRECISION); // dev: rate underflow // (cashAmount / fee) * (totalfCash + totalCash) // Precision: TOKEN_PRECISION ^ 2 derivative = cashAmount .mul(totalfCash.add(totalCashUnderlying)) .divInRatePrecision(feeRate); } else { // Borrowing exchangeRate = exchangeRate.mulInRatePrecision(feeRate); require(exchangeRate >= Constants.RATE_PRECISION); // dev: rate underflow // (cashAmount * fee) * (totalfCash + totalCash) // Precision: TOKEN_PRECISION ^ 2 derivative = cashAmount.mulInRatePrecision( feeRate.mul(totalfCash.add(totalCashUnderlying)) ); } // 1 - numerator / denominator // Precision: TOKEN_PRECISION derivative = Constants.INTERNAL_TOKEN_PRECISION.sub(derivative.div(denominator)); // f(fCash) = cashAmount * exchangeRate * fee + fCash // NOTE: exchangeRate at this point already has the fee taken into account int256 numerator = cashAmount.mulInRatePrecision(exchangeRate); numerator = numerator.add(fCashGuess); // f(fCash) / f'(fCash), note that they are both denominated as cashAmount so use TOKEN_PRECISION // here instead of RATE_PRECISION return numerator.mul(Constants.INTERNAL_TOKEN_PRECISION).div(derivative); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../../global/Types.sol"; import "../../global/LibStorage.sol"; import "../../global/Constants.sol"; import "../../math/SafeInt256.sol"; import "interfaces/notional/AssetRateAdapter.sol"; library AssetRate { using SafeInt256 for int256; event SetSettlementRate(uint256 indexed currencyId, uint256 indexed maturity, uint128 rate); // Asset rates are in 1e18 decimals (cToken exchange rates), internal balances // are in 1e8 decimals. Therefore we leave this as 1e18 / 1e8 = 1e10 int256 private constant ASSET_RATE_DECIMAL_DIFFERENCE = 1e10; /// @notice Converts an internal asset cash value to its underlying token value. /// @param ar exchange rate object between asset and underlying /// @param assetBalance amount to convert to underlying function convertToUnderlying(AssetRateParameters memory ar, int256 assetBalance) internal pure returns (int256) { // Calculation here represents: // rate * balance * internalPrecision / rateDecimals * underlyingPrecision int256 underlyingBalance = ar.rate .mul(assetBalance) .div(ASSET_RATE_DECIMAL_DIFFERENCE) .div(ar.underlyingDecimals); return underlyingBalance; } /// @notice Converts an internal underlying cash value to its asset cash value /// @param ar exchange rate object between asset and underlying /// @param underlyingBalance amount to convert to asset cash, denominated in internal token precision function convertFromUnderlying(AssetRateParameters memory ar, int256 underlyingBalance) internal pure returns (int256) { // Calculation here represents: // rateDecimals * balance * underlyingPrecision / rate * internalPrecision int256 assetBalance = underlyingBalance .mul(ASSET_RATE_DECIMAL_DIFFERENCE) .mul(ar.underlyingDecimals) .div(ar.rate); return assetBalance; } /// @notice Returns the current per block supply rate, is used when calculating oracle rates /// for idiosyncratic fCash with a shorter duration than the 3 month maturity. function getSupplyRate(AssetRateParameters memory ar) internal view returns (uint256) { // If the rate oracle is not set, the asset is not interest bearing and has an oracle rate of zero. if (address(ar.rateOracle) == address(0)) return 0; uint256 rate = ar.rateOracle.getAnnualizedSupplyRate(); // Zero supply rate is valid since this is an interest rate, we do not divide by // the supply rate so we do not get div by zero errors. require(rate >= 0); // dev: invalid supply rate return rate; } function _getAssetRateStorage(uint256 currencyId) private view returns (AssetRateAdapter rateOracle, uint8 underlyingDecimalPlaces) { mapping(uint256 => AssetRateStorage) storage store = LibStorage.getAssetRateStorage(); AssetRateStorage storage ar = store[currencyId]; rateOracle = AssetRateAdapter(ar.rateOracle); underlyingDecimalPlaces = ar.underlyingDecimalPlaces; } /// @notice Gets an asset rate using a view function, does not accrue interest so the /// exchange rate will not be up to date. Should only be used for non-stateful methods function _getAssetRateView(uint256 currencyId) private view returns ( int256, AssetRateAdapter, uint8 ) { (AssetRateAdapter rateOracle, uint8 underlyingDecimalPlaces) = _getAssetRateStorage(currencyId); int256 rate; if (address(rateOracle) == address(0)) { // If no rate oracle is set, then set this to the identity rate = ASSET_RATE_DECIMAL_DIFFERENCE; // This will get raised to 10^x and return 1, will not end up with div by zero underlyingDecimalPlaces = 0; } else { rate = rateOracle.getExchangeRateView(); require(rate > 0); // dev: invalid exchange rate } return (rate, rateOracle, underlyingDecimalPlaces); } /// @notice Gets an asset rate using a stateful function, accrues interest so the /// exchange rate will be up to date for the current block. function _getAssetRateStateful(uint256 currencyId) private returns ( int256, AssetRateAdapter, uint8 ) { (AssetRateAdapter rateOracle, uint8 underlyingDecimalPlaces) = _getAssetRateStorage(currencyId); int256 rate; if (address(rateOracle) == address(0)) { // If no rate oracle is set, then set this to the identity rate = ASSET_RATE_DECIMAL_DIFFERENCE; // This will get raised to 10^x and return 1, will not end up with div by zero underlyingDecimalPlaces = 0; } else { rate = rateOracle.getExchangeRateStateful(); require(rate > 0); // dev: invalid exchange rate } return (rate, rateOracle, underlyingDecimalPlaces); } /// @notice Returns an asset rate object using the view method function buildAssetRateView(uint256 currencyId) internal view returns (AssetRateParameters memory) { (int256 rate, AssetRateAdapter rateOracle, uint8 underlyingDecimalPlaces) = _getAssetRateView(currencyId); return AssetRateParameters({ rateOracle: rateOracle, rate: rate, // No overflow, restricted on storage underlyingDecimals: int256(10**underlyingDecimalPlaces) }); } /// @notice Returns an asset rate object using the stateful method function buildAssetRateStateful(uint256 currencyId) internal returns (AssetRateParameters memory) { (int256 rate, AssetRateAdapter rateOracle, uint8 underlyingDecimalPlaces) = _getAssetRateStateful(currencyId); return AssetRateParameters({ rateOracle: rateOracle, rate: rate, // No overflow, restricted on storage underlyingDecimals: int256(10**underlyingDecimalPlaces) }); } /// @dev Gets a settlement rate object function _getSettlementRateStorage(uint256 currencyId, uint256 maturity) private view returns ( int256 settlementRate, uint8 underlyingDecimalPlaces ) { mapping(uint256 => mapping(uint256 => SettlementRateStorage)) storage store = LibStorage.getSettlementRateStorage(); SettlementRateStorage storage rateStorage = store[currencyId][maturity]; settlementRate = rateStorage.settlementRate; underlyingDecimalPlaces = rateStorage.underlyingDecimalPlaces; } /// @notice Returns a settlement rate object using the view method function buildSettlementRateView(uint256 currencyId, uint256 maturity) internal view returns (AssetRateParameters memory) { // prettier-ignore ( int256 settlementRate, uint8 underlyingDecimalPlaces ) = _getSettlementRateStorage(currencyId, maturity); // Asset exchange rates cannot be zero if (settlementRate == 0) { // If settlement rate has not been set then we need to fetch it // prettier-ignore ( settlementRate, /* address */, underlyingDecimalPlaces ) = _getAssetRateView(currencyId); } return AssetRateParameters( AssetRateAdapter(address(0)), settlementRate, // No overflow, restricted on storage int256(10**underlyingDecimalPlaces) ); } /// @notice Returns a settlement rate object and sets the rate if it has not been set yet function buildSettlementRateStateful( uint256 currencyId, uint256 maturity, uint256 blockTime ) internal returns (AssetRateParameters memory) { (int256 settlementRate, uint8 underlyingDecimalPlaces) = _getSettlementRateStorage(currencyId, maturity); if (settlementRate == 0) { // Settlement rate has not yet been set, set it in this branch AssetRateAdapter rateOracle; // If rate oracle == 0 then this will return the identity settlement rate // prettier-ignore ( settlementRate, rateOracle, underlyingDecimalPlaces ) = _getAssetRateStateful(currencyId); if (address(rateOracle) != address(0)) { mapping(uint256 => mapping(uint256 => SettlementRateStorage)) storage store = LibStorage.getSettlementRateStorage(); // Only need to set settlement rates when the rate oracle is set (meaning the asset token has // a conversion rate to an underlying). If not set then the asset cash always settles to underlying at a 1-1 // rate since they are the same. require(blockTime != 0 && blockTime <= type(uint40).max); // dev: settlement rate timestamp overflow require(0 < settlementRate && settlementRate <= type(uint128).max); // dev: settlement rate overflow SettlementRateStorage storage rateStorage = store[currencyId][maturity]; rateStorage.blockTime = uint40(blockTime); rateStorage.settlementRate = uint128(settlementRate); rateStorage.underlyingDecimalPlaces = underlyingDecimalPlaces; emit SetSettlementRate(currencyId, maturity, uint128(settlementRate)); } } return AssetRateParameters( AssetRateAdapter(address(0)), settlementRate, // No overflow, restricted on storage int256(10**underlyingDecimalPlaces) ); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../../global/Constants.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; library DateTime { using SafeMath for uint256; /// @notice Returns the current reference time which is how all the AMM dates are calculated. function getReferenceTime(uint256 blockTime) internal pure returns (uint256) { require(blockTime >= Constants.QUARTER); return blockTime - (blockTime % Constants.QUARTER); } /// @notice Truncates a date to midnight UTC time function getTimeUTC0(uint256 time) internal pure returns (uint256) { require(time >= Constants.DAY); return time - (time % Constants.DAY); } /// @notice These are the predetermined market offsets for trading /// @dev Markets are 1-indexed because the 0 index means that no markets are listed for the cash group. function getTradedMarket(uint256 index) internal pure returns (uint256) { if (index == 1) return Constants.QUARTER; if (index == 2) return 2 * Constants.QUARTER; if (index == 3) return Constants.YEAR; if (index == 4) return 2 * Constants.YEAR; if (index == 5) return 5 * Constants.YEAR; if (index == 6) return 10 * Constants.YEAR; if (index == 7) return 20 * Constants.YEAR; revert("Invalid index"); } /// @notice Determines if the maturity falls on one of the valid on chain market dates. function isValidMarketMaturity( uint256 maxMarketIndex, uint256 maturity, uint256 blockTime ) internal pure returns (bool) { require(maxMarketIndex > 0, "CG: no markets listed"); require(maxMarketIndex <= Constants.MAX_TRADED_MARKET_INDEX, "CG: market index bound"); if (maturity % Constants.QUARTER != 0) return false; uint256 tRef = DateTime.getReferenceTime(blockTime); for (uint256 i = 1; i <= maxMarketIndex; i++) { if (maturity == tRef.add(DateTime.getTradedMarket(i))) return true; } return false; } /// @notice Determines if an idiosyncratic maturity is valid and returns the bit reference that is the case. function isValidMaturity( uint256 maxMarketIndex, uint256 maturity, uint256 blockTime ) internal pure returns (bool) { uint256 tRef = DateTime.getReferenceTime(blockTime); uint256 maxMaturity = tRef.add(DateTime.getTradedMarket(maxMarketIndex)); // Cannot trade past max maturity if (maturity > maxMaturity) return false; // prettier-ignore (/* */, bool isValid) = DateTime.getBitNumFromMaturity(blockTime, maturity); return isValid; } /// @notice Returns the market index for a given maturity, if the maturity is idiosyncratic /// will return the nearest market index that is larger than the maturity. /// @return uint marketIndex, bool isIdiosyncratic function getMarketIndex( uint256 maxMarketIndex, uint256 maturity, uint256 blockTime ) internal pure returns (uint256, bool) { require(maxMarketIndex > 0, "CG: no markets listed"); require(maxMarketIndex <= Constants.MAX_TRADED_MARKET_INDEX, "CG: market index bound"); uint256 tRef = DateTime.getReferenceTime(blockTime); for (uint256 i = 1; i <= maxMarketIndex; i++) { uint256 marketMaturity = tRef.add(DateTime.getTradedMarket(i)); // If market matches then is not idiosyncratic if (marketMaturity == maturity) return (i, false); // Returns the market that is immediately greater than the maturity if (marketMaturity > maturity) return (i, true); } revert("CG: no market found"); } /// @notice Given a bit number and the reference time of the first bit, returns the bit number /// of a given maturity. /// @return bitNum and a true or false if the maturity falls on the exact bit function getBitNumFromMaturity(uint256 blockTime, uint256 maturity) internal pure returns (uint256, bool) { uint256 blockTimeUTC0 = getTimeUTC0(blockTime); // Maturities must always divide days evenly if (maturity % Constants.DAY != 0) return (0, false); // Maturity cannot be in the past if (blockTimeUTC0 >= maturity) return (0, false); // Overflow check done above // daysOffset has no remainders, checked above uint256 daysOffset = (maturity - blockTimeUTC0) / Constants.DAY; // These if statements need to fall through to the next one if (daysOffset <= Constants.MAX_DAY_OFFSET) { return (daysOffset, true); } else if (daysOffset <= Constants.MAX_WEEK_OFFSET) { // (daysOffset - MAX_DAY_OFFSET) is the days overflow into the week portion, must be > 0 // (blockTimeUTC0 % WEEK) / DAY is the offset into the week portion // This returns the offset from the previous max offset in days uint256 offsetInDays = daysOffset - Constants.MAX_DAY_OFFSET + (blockTimeUTC0 % Constants.WEEK) / Constants.DAY; return ( // This converts the offset in days to its corresponding bit position, truncating down // if it does not divide evenly into DAYS_IN_WEEK Constants.WEEK_BIT_OFFSET + offsetInDays / Constants.DAYS_IN_WEEK, (offsetInDays % Constants.DAYS_IN_WEEK) == 0 ); } else if (daysOffset <= Constants.MAX_MONTH_OFFSET) { uint256 offsetInDays = daysOffset - Constants.MAX_WEEK_OFFSET + (blockTimeUTC0 % Constants.MONTH) / Constants.DAY; return ( Constants.MONTH_BIT_OFFSET + offsetInDays / Constants.DAYS_IN_MONTH, (offsetInDays % Constants.DAYS_IN_MONTH) == 0 ); } else if (daysOffset <= Constants.MAX_QUARTER_OFFSET) { uint256 offsetInDays = daysOffset - Constants.MAX_MONTH_OFFSET + (blockTimeUTC0 % Constants.QUARTER) / Constants.DAY; return ( Constants.QUARTER_BIT_OFFSET + offsetInDays / Constants.DAYS_IN_QUARTER, (offsetInDays % Constants.DAYS_IN_QUARTER) == 0 ); } // This is the maximum 1-indexed bit num, it is never valid because it is beyond the 20 // year max maturity return (256, false); } /// @notice Given a bit number and a block time returns the maturity that the bit number /// should reference. Bit numbers are one indexed. function getMaturityFromBitNum(uint256 blockTime, uint256 bitNum) internal pure returns (uint256) { require(bitNum != 0); // dev: cash group get maturity from bit num is zero require(bitNum <= 256); // dev: cash group get maturity from bit num overflow uint256 blockTimeUTC0 = getTimeUTC0(blockTime); uint256 firstBit; if (bitNum <= Constants.WEEK_BIT_OFFSET) { return blockTimeUTC0 + bitNum * Constants.DAY; } else if (bitNum <= Constants.MONTH_BIT_OFFSET) { firstBit = blockTimeUTC0 + Constants.MAX_DAY_OFFSET * Constants.DAY - // This backs up to the day that is divisible by a week (blockTimeUTC0 % Constants.WEEK); return firstBit + (bitNum - Constants.WEEK_BIT_OFFSET) * Constants.WEEK; } else if (bitNum <= Constants.QUARTER_BIT_OFFSET) { firstBit = blockTimeUTC0 + Constants.MAX_WEEK_OFFSET * Constants.DAY - (blockTimeUTC0 % Constants.MONTH); return firstBit + (bitNum - Constants.MONTH_BIT_OFFSET) * Constants.MONTH; } else { firstBit = blockTimeUTC0 + Constants.MAX_MONTH_OFFSET * Constants.DAY - (blockTimeUTC0 % Constants.QUARTER); return firstBit + (bitNum - Constants.QUARTER_BIT_OFFSET) * Constants.QUARTER; } } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "./Incentives.sol"; import "./TokenHandler.sol"; import "../AccountContextHandler.sol"; import "../../global/Types.sol"; import "../../global/Constants.sol"; import "../../math/SafeInt256.sol"; import "../../math/FloatingPoint56.sol"; library BalanceHandler { using SafeInt256 for int256; using TokenHandler for Token; using AssetRate for AssetRateParameters; using AccountContextHandler for AccountContext; /// @notice Emitted when a cash balance changes event CashBalanceChange(address indexed account, uint16 indexed currencyId, int256 netCashChange); /// @notice Emitted when nToken supply changes (not the same as transfers) event nTokenSupplyChange(address indexed account, uint16 indexed currencyId, int256 tokenSupplyChange); /// @notice Emitted when reserve fees are accrued event ReserveFeeAccrued(uint16 indexed currencyId, int256 fee); /// @notice Deposits asset tokens into an account /// @dev Handles two special cases when depositing tokens into an account. /// - If a token has transfer fees then the amount specified does not equal the amount that the contract /// will receive. Complete the deposit here rather than in finalize so that the contract has the correct /// balance to work with. /// - Force a transfer before finalize to allow a different account to deposit into an account /// @return Returns two values: /// - assetAmountInternal which is the converted asset amount accounting for transfer fees /// - assetAmountTransferred which is the internal precision amount transferred into the account function depositAssetToken( BalanceState memory balanceState, address account, int256 assetAmountExternal, bool forceTransfer ) internal returns (int256) { if (assetAmountExternal == 0) return 0; require(assetAmountExternal > 0); // dev: deposit asset token amount negative Token memory token = TokenHandler.getAssetToken(balanceState.currencyId); int256 assetAmountInternal = token.convertToInternal(assetAmountExternal); // Force transfer is used to complete the transfer before going to finalize if (token.hasTransferFee || forceTransfer) { // If the token has a transfer fee the deposit amount may not equal the actual amount // that the contract will receive. We handle the deposit here and then update the netCashChange // accordingly which is denominated in internal precision. int256 assetAmountExternalPrecisionFinal = token.transfer(account, assetAmountExternal); // Convert the external precision to internal, it's possible that we lose dust amounts here but // this is unavoidable because we do not know how transfer fees are calculated. assetAmountInternal = token.convertToInternal(assetAmountExternalPrecisionFinal); // Transfer has been called balanceState.netCashChange = balanceState.netCashChange.add(assetAmountInternal); return assetAmountInternal; } else { // Otherwise add the asset amount here. It may be net off later and we want to only do // a single transfer during the finalize method. Use internal precision to ensure that internal accounting // and external account remain in sync. // Transfer will be deferred balanceState.netAssetTransferInternalPrecision = balanceState .netAssetTransferInternalPrecision .add(assetAmountInternal); // Returns the converted assetAmountExternal to the internal amount return assetAmountInternal; } } /// @notice Handle deposits of the underlying token /// @dev In this case we must wrap the underlying token into an asset token, ensuring that we do not end up /// with any underlying tokens left as dust on the contract. function depositUnderlyingToken( BalanceState memory balanceState, address account, int256 underlyingAmountExternal ) internal returns (int256) { if (underlyingAmountExternal == 0) return 0; require(underlyingAmountExternal > 0); // dev: deposit underlying token negative Token memory underlyingToken = TokenHandler.getUnderlyingToken(balanceState.currencyId); // This is the exact amount of underlying tokens the account has in external precision. if (underlyingToken.tokenType == TokenType.Ether) { // Underflow checked above require(uint256(underlyingAmountExternal) == msg.value, "ETH Balance"); } else { underlyingAmountExternal = underlyingToken.transfer(account, underlyingAmountExternal); } Token memory assetToken = TokenHandler.getAssetToken(balanceState.currencyId); // Tokens that are not mintable like cTokens will be deposited as assetTokens require(assetToken.tokenType == TokenType.cToken || assetToken.tokenType == TokenType.cETH); // dev: deposit underlying token invalid token type int256 assetTokensReceivedExternalPrecision = assetToken.mint(SafeInt256.toUint(underlyingAmountExternal)); // cTokens match INTERNAL_TOKEN_PRECISION so this will short circuit but we leave this here in case a different // type of asset token is listed in the future. It's possible if those tokens have a different precision dust may // accrue but that is not relevant now. int256 assetTokensReceivedInternal = assetToken.convertToInternal(assetTokensReceivedExternalPrecision); // Transfer / mint has taken effect balanceState.netCashChange = balanceState.netCashChange.add(assetTokensReceivedInternal); return assetTokensReceivedInternal; } /// @notice Finalizes an account's balances, handling any transfer logic required /// @dev This method SHOULD NOT be used for nToken accounts, for that use setBalanceStorageForNToken /// as the nToken is limited in what types of balances it can hold. function finalize( BalanceState memory balanceState, address account, AccountContext memory accountContext, bool redeemToUnderlying ) internal returns (int256 transferAmountExternal) { bool mustUpdate; if (balanceState.netNTokenTransfer < 0) { require( balanceState.storedNTokenBalance .add(balanceState.netNTokenSupplyChange) .add(balanceState.netNTokenTransfer) >= 0, "Neg nToken" ); } if (balanceState.netAssetTransferInternalPrecision < 0) { require( balanceState.storedCashBalance .add(balanceState.netCashChange) .add(balanceState.netAssetTransferInternalPrecision) >= 0, "Neg Cash" ); } // Transfer amount is checked inside finalize transfers in case when converting to external we // round down to zero. This returns the actual net transfer in internal precision as well. ( transferAmountExternal, balanceState.netAssetTransferInternalPrecision ) = _finalizeTransfers(balanceState, account, redeemToUnderlying); // No changes to total cash after this point int256 totalCashChange = balanceState.netCashChange.add(balanceState.netAssetTransferInternalPrecision); if (totalCashChange != 0) { balanceState.storedCashBalance = balanceState.storedCashBalance.add(totalCashChange); mustUpdate = true; emit CashBalanceChange( account, uint16(balanceState.currencyId), totalCashChange ); } if (balanceState.netNTokenTransfer != 0 || balanceState.netNTokenSupplyChange != 0) { // It's crucial that incentives are claimed before we do any sort of nToken transfer to prevent gaming // of the system. This method will update the lastClaimTime time and lastIntegralTotalSupply in balance // state in place. Incentives.claimIncentives(balanceState, account); // nTokens are within the notional system so we can update balances directly. balanceState.storedNTokenBalance = balanceState .storedNTokenBalance .add(balanceState.netNTokenTransfer) .add(balanceState.netNTokenSupplyChange); if (balanceState.netNTokenSupplyChange != 0) { emit nTokenSupplyChange( account, uint16(balanceState.currencyId), balanceState.netNTokenSupplyChange ); } mustUpdate = true; } if (mustUpdate) { _setBalanceStorage( account, balanceState.currencyId, balanceState.storedCashBalance, balanceState.storedNTokenBalance, balanceState.lastClaimTime, balanceState.lastClaimIntegralSupply ); } accountContext.setActiveCurrency( balanceState.currencyId, // Set active currency to true if either balance is non-zero balanceState.storedCashBalance != 0 || balanceState.storedNTokenBalance != 0, Constants.ACTIVE_IN_BALANCES ); if (balanceState.storedCashBalance < 0) { // NOTE: HAS_CASH_DEBT cannot be extinguished except by a free collateral check where all balances // are examined accountContext.hasDebt = accountContext.hasDebt | Constants.HAS_CASH_DEBT; } } /// @dev Returns the amount transferred in underlying or asset terms depending on how redeem to underlying /// is specified. function _finalizeTransfers( BalanceState memory balanceState, address account, bool redeemToUnderlying ) private returns (int256 actualTransferAmountExternal, int256 assetTransferAmountInternal) { Token memory assetToken = TokenHandler.getAssetToken(balanceState.currencyId); // Dust accrual to the protocol is possible if the token decimals is less than internal token precision. // See the comments in TokenHandler.convertToExternal and TokenHandler.convertToInternal int256 assetTransferAmountExternal = assetToken.convertToExternal(balanceState.netAssetTransferInternalPrecision); if (assetTransferAmountExternal == 0) { return (0, 0); } else if (redeemToUnderlying && assetTransferAmountExternal < 0) { // We only do the redeem to underlying if the asset transfer amount is less than zero. If it is greater than // zero then we will do a normal transfer instead. // We use the internal amount here and then scale it to the external amount so that there is // no loss of precision between our internal accounting and the external account. In this case // there will be no dust accrual in underlying tokens since we will transfer the exact amount // of underlying that was received. Token memory underlyingToken = TokenHandler.getUnderlyingToken(balanceState.currencyId); // underlyingAmountExternal is converted from uint to int inside redeem, must be positive int256 underlyingAmountExternal = assetToken.redeem( underlyingToken, uint256(assetTransferAmountExternal.neg()) ); // Withdraws the underlying amount out to the destination account actualTransferAmountExternal = underlyingToken.transfer( account, underlyingAmountExternal.neg() ); // In this case we're transferring underlying tokens, we want to convert the internal // asset transfer amount to store in cash balances assetTransferAmountInternal = assetToken.convertToInternal(assetTransferAmountExternal); } else { actualTransferAmountExternal = assetToken.transfer(account, assetTransferAmountExternal); // Convert the actual transferred amount assetTransferAmountInternal = assetToken.convertToInternal(actualTransferAmountExternal); } } /// @notice Special method for settling negative current cash debts. This occurs when an account /// has a negative fCash balance settle to cash. A settler may come and force the account to borrow /// at the prevailing 3 month rate /// @dev Use this method to avoid any nToken and transfer logic in finalize which is unnecessary. function setBalanceStorageForSettleCashDebt( address account, CashGroupParameters memory cashGroup, int256 amountToSettleAsset, AccountContext memory accountContext ) internal returns (int256) { require(amountToSettleAsset >= 0); // dev: amount to settle negative (int256 cashBalance, int256 nTokenBalance, uint256 lastClaimTime, uint256 lastClaimIntegralSupply) = getBalanceStorage(account, cashGroup.currencyId); // Prevents settlement of positive balances require(cashBalance < 0, "Invalid settle balance"); if (amountToSettleAsset == 0) { // Symbolizes that the entire debt should be settled amountToSettleAsset = cashBalance.neg(); cashBalance = 0; } else { // A partial settlement of the debt require(amountToSettleAsset <= cashBalance.neg(), "Invalid amount to settle"); cashBalance = cashBalance.add(amountToSettleAsset); } // NOTE: we do not update HAS_CASH_DEBT here because it is possible that the other balances // also have cash debts if (cashBalance == 0 && nTokenBalance == 0) { accountContext.setActiveCurrency( cashGroup.currencyId, false, Constants.ACTIVE_IN_BALANCES ); } _setBalanceStorage( account, cashGroup.currencyId, cashBalance, nTokenBalance, lastClaimTime, lastClaimIntegralSupply ); // Emit the event here, we do not call finalize emit CashBalanceChange(account, cashGroup.currencyId, amountToSettleAsset); return amountToSettleAsset; } /// @notice Helper method for settling the output of the SettleAssets method function finalizeSettleAmounts( address account, AccountContext memory accountContext, SettleAmount[] memory settleAmounts ) internal { for (uint256 i = 0; i < settleAmounts.length; i++) { SettleAmount memory amt = settleAmounts[i]; if (amt.netCashChange == 0) continue; ( int256 cashBalance, int256 nTokenBalance, uint256 lastClaimTime, uint256 lastClaimIntegralSupply ) = getBalanceStorage(account, amt.currencyId); cashBalance = cashBalance.add(amt.netCashChange); accountContext.setActiveCurrency( amt.currencyId, cashBalance != 0 || nTokenBalance != 0, Constants.ACTIVE_IN_BALANCES ); if (cashBalance < 0) { accountContext.hasDebt = accountContext.hasDebt | Constants.HAS_CASH_DEBT; } emit CashBalanceChange( account, uint16(amt.currencyId), amt.netCashChange ); _setBalanceStorage( account, amt.currencyId, cashBalance, nTokenBalance, lastClaimTime, lastClaimIntegralSupply ); } } /// @notice Special method for setting balance storage for nToken function setBalanceStorageForNToken( address nTokenAddress, uint256 currencyId, int256 cashBalance ) internal { require(cashBalance >= 0); // dev: invalid nToken cash balance _setBalanceStorage(nTokenAddress, currencyId, cashBalance, 0, 0, 0); } /// @notice increments fees to the reserve function incrementFeeToReserve(uint256 currencyId, int256 fee) internal { require(fee >= 0); // dev: invalid fee // prettier-ignore (int256 totalReserve, /* */, /* */, /* */) = getBalanceStorage(Constants.RESERVE, currencyId); totalReserve = totalReserve.add(fee); _setBalanceStorage(Constants.RESERVE, currencyId, totalReserve, 0, 0, 0); emit ReserveFeeAccrued(uint16(currencyId), fee); } /// @notice Sets internal balance storage. function _setBalanceStorage( address account, uint256 currencyId, int256 cashBalance, int256 nTokenBalance, uint256 lastClaimTime, uint256 lastClaimIntegralSupply ) private { mapping(address => mapping(uint256 => BalanceStorage)) storage store = LibStorage.getBalanceStorage(); BalanceStorage storage balanceStorage = store[account][currencyId]; require(cashBalance >= type(int88).min && cashBalance <= type(int88).max); // dev: stored cash balance overflow // Allows for 12 quadrillion nToken balance in 1e8 decimals before overflow require(nTokenBalance >= 0 && nTokenBalance <= type(uint80).max); // dev: stored nToken balance overflow require(lastClaimTime <= type(uint32).max); // dev: last claim time overflow balanceStorage.nTokenBalance = uint80(nTokenBalance); balanceStorage.lastClaimTime = uint32(lastClaimTime); balanceStorage.cashBalance = int88(cashBalance); // Last claim supply is stored in a "floating point" storage slot that does not maintain exact precision but // is also not limited by storage overflows. `packTo56Bits` will ensure that the the returned value will fit // in 56 bits (7 bytes) balanceStorage.packedLastClaimIntegralSupply = FloatingPoint56.packTo56Bits(lastClaimIntegralSupply); } /// @notice Gets internal balance storage, nTokens are stored alongside cash balances function getBalanceStorage(address account, uint256 currencyId) internal view returns ( int256 cashBalance, int256 nTokenBalance, uint256 lastClaimTime, uint256 lastClaimIntegralSupply ) { mapping(address => mapping(uint256 => BalanceStorage)) storage store = LibStorage.getBalanceStorage(); BalanceStorage storage balanceStorage = store[account][currencyId]; nTokenBalance = balanceStorage.nTokenBalance; lastClaimTime = balanceStorage.lastClaimTime; lastClaimIntegralSupply = FloatingPoint56.unpackFrom56Bits(balanceStorage.packedLastClaimIntegralSupply); cashBalance = balanceStorage.cashBalance; } /// @notice Loads a balance state memory object /// @dev Balance state objects occupy a lot of memory slots, so this method allows /// us to reuse them if possible function loadBalanceState( BalanceState memory balanceState, address account, uint16 currencyId, AccountContext memory accountContext ) internal view { require(0 < currencyId && currencyId <= Constants.MAX_CURRENCIES); // dev: invalid currency id balanceState.currencyId = currencyId; if (accountContext.isActiveInBalances(currencyId)) { ( balanceState.storedCashBalance, balanceState.storedNTokenBalance, balanceState.lastClaimTime, balanceState.lastClaimIntegralSupply ) = getBalanceStorage(account, currencyId); } else { balanceState.storedCashBalance = 0; balanceState.storedNTokenBalance = 0; balanceState.lastClaimTime = 0; balanceState.lastClaimIntegralSupply = 0; } balanceState.netCashChange = 0; balanceState.netAssetTransferInternalPrecision = 0; balanceState.netNTokenTransfer = 0; balanceState.netNTokenSupplyChange = 0; } /// @notice Used when manually claiming incentives in nTokenAction. Also sets the balance state /// to storage to update the lastClaimTime and lastClaimIntegralSupply function claimIncentivesManual(BalanceState memory balanceState, address account) internal returns (uint256) { uint256 incentivesClaimed = Incentives.claimIncentives(balanceState, account); _setBalanceStorage( account, balanceState.currencyId, balanceState.storedCashBalance, balanceState.storedNTokenBalance, balanceState.lastClaimTime, balanceState.lastClaimIntegralSupply ); return incentivesClaimed; } } // SPDX-License-Identifier: BSD-4-Clause /* * ABDK Math 64.64 Smart Contract Library. Copyright © 2019 by ABDK Consulting. * Author: Mikhail Vladimirov <[email protected]> */ pragma solidity ^0.5.0 || ^0.6.0 || ^0.7.0; /** * Smart contract library of mathematical functions operating with signed * 64.64-bit fixed point numbers. Signed 64.64-bit fixed point number is * basically a simple fraction whose numerator is signed 128-bit integer and * denominator is 2^64. As long as denominator is always the same, there is no * need to store it, thus in Solidity signed 64.64-bit fixed point numbers are * represented by int128 type holding only the numerator. */ library ABDKMath64x64 { /* * Minimum value signed 64.64-bit fixed point number may have. */ int128 private constant MIN_64x64 = -0x80000000000000000000000000000000; /* * Maximum value signed 64.64-bit fixed point number may have. */ int128 private constant MAX_64x64 = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; /** * Convert signed 256-bit integer number into signed 64.64-bit fixed point * number. Revert on overflow. * * @param x signed 256-bit integer number * @return signed 64.64-bit fixed point number */ function fromInt (int256 x) internal pure returns (int128) { require (x >= -0x8000000000000000 && x <= 0x7FFFFFFFFFFFFFFF); return int128 (x << 64); } /** * Convert signed 64.64 fixed point number into signed 64-bit integer number * rounding down. * * @param x signed 64.64-bit fixed point number * @return signed 64-bit integer number */ function toInt (int128 x) internal pure returns (int64) { return int64 (x >> 64); } /** * Convert unsigned 256-bit integer number into signed 64.64-bit fixed point * number. Revert on overflow. * * @param x unsigned 256-bit integer number * @return signed 64.64-bit fixed point number */ function fromUInt (uint256 x) internal pure returns (int128) { require (x <= 0x7FFFFFFFFFFFFFFF); return int128 (x << 64); } /** * Convert signed 64.64 fixed point number into unsigned 64-bit integer * number rounding down. Revert on underflow. * * @param x signed 64.64-bit fixed point number * @return unsigned 64-bit integer number */ function toUInt (int128 x) internal pure returns (uint64) { require (x >= 0); return uint64 (x >> 64); } /** * Convert signed 128.128 fixed point number into signed 64.64-bit fixed point * number rounding down. Revert on overflow. * * @param x signed 128.128-bin fixed point number * @return signed 64.64-bit fixed point number */ function from128x128 (int256 x) internal pure returns (int128) { int256 result = x >> 64; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } /** * Convert signed 64.64 fixed point number into signed 128.128 fixed point * number. * * @param x signed 64.64-bit fixed point number * @return signed 128.128 fixed point number */ function to128x128 (int128 x) internal pure returns (int256) { return int256 (x) << 64; } /** * Calculate x + y. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function add (int128 x, int128 y) internal pure returns (int128) { int256 result = int256(x) + y; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } /** * Calculate x - y. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function sub (int128 x, int128 y) internal pure returns (int128) { int256 result = int256(x) - y; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } /** * Calculate x * y rounding down. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function mul (int128 x, int128 y) internal pure returns (int128) { int256 result = int256(x) * y >> 64; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } /** * Calculate x * y rounding towards zero, where x is signed 64.64 fixed point * number and y is signed 256-bit integer number. Revert on overflow. * * @param x signed 64.64 fixed point number * @param y signed 256-bit integer number * @return signed 256-bit integer number */ function muli (int128 x, int256 y) internal pure returns (int256) { if (x == MIN_64x64) { require (y >= -0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF && y <= 0x1000000000000000000000000000000000000000000000000); return -y << 63; } else { bool negativeResult = false; if (x < 0) { x = -x; negativeResult = true; } if (y < 0) { y = -y; // We rely on overflow behavior here negativeResult = !negativeResult; } uint256 absoluteResult = mulu (x, uint256 (y)); if (negativeResult) { require (absoluteResult <= 0x8000000000000000000000000000000000000000000000000000000000000000); return -int256 (absoluteResult); // We rely on overflow behavior here } else { require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return int256 (absoluteResult); } } } /** * Calculate x * y rounding down, where x is signed 64.64 fixed point number * and y is unsigned 256-bit integer number. Revert on overflow. * * @param x signed 64.64 fixed point number * @param y unsigned 256-bit integer number * @return unsigned 256-bit integer number */ function mulu (int128 x, uint256 y) internal pure returns (uint256) { if (y == 0) return 0; require (x >= 0); uint256 lo = (uint256 (x) * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) >> 64; uint256 hi = uint256 (x) * (y >> 128); require (hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); hi <<= 64; require (hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF - lo); return hi + lo; } /** * Calculate x / y rounding towards zero. Revert on overflow or when y is * zero. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function div (int128 x, int128 y) internal pure returns (int128) { require (y != 0); int256 result = (int256 (x) << 64) / y; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } /** * Calculate x / y rounding towards zero, where x and y are signed 256-bit * integer numbers. Revert on overflow or when y is zero. * * @param x signed 256-bit integer number * @param y signed 256-bit integer number * @return signed 64.64-bit fixed point number */ function divi (int256 x, int256 y) internal pure returns (int128) { require (y != 0); bool negativeResult = false; if (x < 0) { x = -x; // We rely on overflow behavior here negativeResult = true; } if (y < 0) { y = -y; // We rely on overflow behavior here negativeResult = !negativeResult; } uint128 absoluteResult = divuu (uint256 (x), uint256 (y)); if (negativeResult) { require (absoluteResult <= 0x80000000000000000000000000000000); return -int128 (absoluteResult); // We rely on overflow behavior here } else { require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return int128 (absoluteResult); // We rely on overflow behavior here } } /** * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit * integer numbers. Revert on overflow or when y is zero. * * @param x unsigned 256-bit integer number * @param y unsigned 256-bit integer number * @return signed 64.64-bit fixed point number */ function divu (uint256 x, uint256 y) internal pure returns (int128) { require (y != 0); uint128 result = divuu (x, y); require (result <= uint128 (MAX_64x64)); return int128 (result); } /** * Calculate -x. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function neg (int128 x) internal pure returns (int128) { require (x != MIN_64x64); return -x; } /** * Calculate |x|. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function abs (int128 x) internal pure returns (int128) { require (x != MIN_64x64); return x < 0 ? -x : x; } /** * Calculate 1 / x rounding towards zero. Revert on overflow or when x is * zero. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function inv (int128 x) internal pure returns (int128) { require (x != 0); int256 result = int256 (0x100000000000000000000000000000000) / x; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } /** * Calculate arithmetics average of x and y, i.e. (x + y) / 2 rounding down. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function avg (int128 x, int128 y) internal pure returns (int128) { return int128 ((int256 (x) + int256 (y)) >> 1); } /** * Calculate geometric average of x and y, i.e. sqrt (x * y) rounding down. * Revert on overflow or in case x * y is negative. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function gavg (int128 x, int128 y) internal pure returns (int128) { int256 m = int256 (x) * int256 (y); require (m >= 0); require (m < 0x4000000000000000000000000000000000000000000000000000000000000000); return int128 (sqrtu (uint256 (m))); } /** * Calculate x^y assuming 0^0 is 1, where x is signed 64.64 fixed point number * and y is unsigned 256-bit integer number. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y uint256 value * @return signed 64.64-bit fixed point number */ function pow (int128 x, uint256 y) internal pure returns (int128) { bool negative = x < 0 && y & 1 == 1; uint256 absX = uint128 (x < 0 ? -x : x); uint256 absResult; absResult = 0x100000000000000000000000000000000; if (absX <= 0x10000000000000000) { absX <<= 63; while (y != 0) { if (y & 0x1 != 0) { absResult = absResult * absX >> 127; } absX = absX * absX >> 127; if (y & 0x2 != 0) { absResult = absResult * absX >> 127; } absX = absX * absX >> 127; if (y & 0x4 != 0) { absResult = absResult * absX >> 127; } absX = absX * absX >> 127; if (y & 0x8 != 0) { absResult = absResult * absX >> 127; } absX = absX * absX >> 127; y >>= 4; } absResult >>= 64; } else { uint256 absXShift = 63; if (absX < 0x1000000000000000000000000) { absX <<= 32; absXShift -= 32; } if (absX < 0x10000000000000000000000000000) { absX <<= 16; absXShift -= 16; } if (absX < 0x1000000000000000000000000000000) { absX <<= 8; absXShift -= 8; } if (absX < 0x10000000000000000000000000000000) { absX <<= 4; absXShift -= 4; } if (absX < 0x40000000000000000000000000000000) { absX <<= 2; absXShift -= 2; } if (absX < 0x80000000000000000000000000000000) { absX <<= 1; absXShift -= 1; } uint256 resultShift = 0; while (y != 0) { require (absXShift < 64); if (y & 0x1 != 0) { absResult = absResult * absX >> 127; resultShift += absXShift; if (absResult > 0x100000000000000000000000000000000) { absResult >>= 1; resultShift += 1; } } absX = absX * absX >> 127; absXShift <<= 1; if (absX >= 0x100000000000000000000000000000000) { absX >>= 1; absXShift += 1; } y >>= 1; } require (resultShift < 64); absResult >>= 64 - resultShift; } int256 result = negative ? -int256 (absResult) : int256 (absResult); require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } /** * Calculate sqrt (x) rounding down. Revert if x < 0. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function sqrt (int128 x) internal pure returns (int128) { require (x >= 0); return int128 (sqrtu (uint256 (x) << 64)); } /** * Calculate binary logarithm of x. Revert if x <= 0. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function log_2 (int128 x) internal pure returns (int128) { require (x > 0); int256 msb = 0; int256 xc = x; if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; } if (xc >= 0x100000000) { xc >>= 32; msb += 32; } if (xc >= 0x10000) { xc >>= 16; msb += 16; } if (xc >= 0x100) { xc >>= 8; msb += 8; } if (xc >= 0x10) { xc >>= 4; msb += 4; } if (xc >= 0x4) { xc >>= 2; msb += 2; } if (xc >= 0x2) msb += 1; // No need to shift xc anymore int256 result = msb - 64 << 64; uint256 ux = uint256 (x) << uint256 (127 - msb); for (int256 bit = 0x8000000000000000; bit > 0; bit >>= 1) { ux *= ux; uint256 b = ux >> 255; ux >>= 127 + b; result += bit * int256 (b); } return int128 (result); } /** * Calculate natural logarithm of x. Revert if x <= 0. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function ln (int128 x) internal pure returns (int128) { require (x > 0); return int128 ( uint256 (log_2 (x)) * 0xB17217F7D1CF79ABC9E3B39803F2F6AF >> 128); } /** * Calculate binary exponent of x. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function exp_2 (int128 x) internal pure returns (int128) { require (x < 0x400000000000000000); // Overflow if (x < -0x400000000000000000) return 0; // Underflow uint256 result = 0x80000000000000000000000000000000; if (x & 0x8000000000000000 > 0) result = result * 0x16A09E667F3BCC908B2FB1366EA957D3E >> 128; if (x & 0x4000000000000000 > 0) result = result * 0x1306FE0A31B7152DE8D5A46305C85EDEC >> 128; if (x & 0x2000000000000000 > 0) result = result * 0x1172B83C7D517ADCDF7C8C50EB14A791F >> 128; if (x & 0x1000000000000000 > 0) result = result * 0x10B5586CF9890F6298B92B71842A98363 >> 128; if (x & 0x800000000000000 > 0) result = result * 0x1059B0D31585743AE7C548EB68CA417FD >> 128; if (x & 0x400000000000000 > 0) result = result * 0x102C9A3E778060EE6F7CACA4F7A29BDE8 >> 128; if (x & 0x200000000000000 > 0) result = result * 0x10163DA9FB33356D84A66AE336DCDFA3F >> 128; if (x & 0x100000000000000 > 0) result = result * 0x100B1AFA5ABCBED6129AB13EC11DC9543 >> 128; if (x & 0x80000000000000 > 0) result = result * 0x10058C86DA1C09EA1FF19D294CF2F679B >> 128; if (x & 0x40000000000000 > 0) result = result * 0x1002C605E2E8CEC506D21BFC89A23A00F >> 128; if (x & 0x20000000000000 > 0) result = result * 0x100162F3904051FA128BCA9C55C31E5DF >> 128; if (x & 0x10000000000000 > 0) result = result * 0x1000B175EFFDC76BA38E31671CA939725 >> 128; if (x & 0x8000000000000 > 0) result = result * 0x100058BA01FB9F96D6CACD4B180917C3D >> 128; if (x & 0x4000000000000 > 0) result = result * 0x10002C5CC37DA9491D0985C348C68E7B3 >> 128; if (x & 0x2000000000000 > 0) result = result * 0x1000162E525EE054754457D5995292026 >> 128; if (x & 0x1000000000000 > 0) result = result * 0x10000B17255775C040618BF4A4ADE83FC >> 128; if (x & 0x800000000000 > 0) result = result * 0x1000058B91B5BC9AE2EED81E9B7D4CFAB >> 128; if (x & 0x400000000000 > 0) result = result * 0x100002C5C89D5EC6CA4D7C8ACC017B7C9 >> 128; if (x & 0x200000000000 > 0) result = result * 0x10000162E43F4F831060E02D839A9D16D >> 128; if (x & 0x100000000000 > 0) result = result * 0x100000B1721BCFC99D9F890EA06911763 >> 128; if (x & 0x80000000000 > 0) result = result * 0x10000058B90CF1E6D97F9CA14DBCC1628 >> 128; if (x & 0x40000000000 > 0) result = result * 0x1000002C5C863B73F016468F6BAC5CA2B >> 128; if (x & 0x20000000000 > 0) result = result * 0x100000162E430E5A18F6119E3C02282A5 >> 128; if (x & 0x10000000000 > 0) result = result * 0x1000000B1721835514B86E6D96EFD1BFE >> 128; if (x & 0x8000000000 > 0) result = result * 0x100000058B90C0B48C6BE5DF846C5B2EF >> 128; if (x & 0x4000000000 > 0) result = result * 0x10000002C5C8601CC6B9E94213C72737A >> 128; if (x & 0x2000000000 > 0) result = result * 0x1000000162E42FFF037DF38AA2B219F06 >> 128; if (x & 0x1000000000 > 0) result = result * 0x10000000B17217FBA9C739AA5819F44F9 >> 128; if (x & 0x800000000 > 0) result = result * 0x1000000058B90BFCDEE5ACD3C1CEDC823 >> 128; if (x & 0x400000000 > 0) result = result * 0x100000002C5C85FE31F35A6A30DA1BE50 >> 128; if (x & 0x200000000 > 0) result = result * 0x10000000162E42FF0999CE3541B9FFFCF >> 128; if (x & 0x100000000 > 0) result = result * 0x100000000B17217F80F4EF5AADDA45554 >> 128; if (x & 0x80000000 > 0) result = result * 0x10000000058B90BFBF8479BD5A81B51AD >> 128; if (x & 0x40000000 > 0) result = result * 0x1000000002C5C85FDF84BD62AE30A74CC >> 128; if (x & 0x20000000 > 0) result = result * 0x100000000162E42FEFB2FED257559BDAA >> 128; if (x & 0x10000000 > 0) result = result * 0x1000000000B17217F7D5A7716BBA4A9AE >> 128; if (x & 0x8000000 > 0) result = result * 0x100000000058B90BFBE9DDBAC5E109CCE >> 128; if (x & 0x4000000 > 0) result = result * 0x10000000002C5C85FDF4B15DE6F17EB0D >> 128; if (x & 0x2000000 > 0) result = result * 0x1000000000162E42FEFA494F1478FDE05 >> 128; if (x & 0x1000000 > 0) result = result * 0x10000000000B17217F7D20CF927C8E94C >> 128; if (x & 0x800000 > 0) result = result * 0x1000000000058B90BFBE8F71CB4E4B33D >> 128; if (x & 0x400000 > 0) result = result * 0x100000000002C5C85FDF477B662B26945 >> 128; if (x & 0x200000 > 0) result = result * 0x10000000000162E42FEFA3AE53369388C >> 128; if (x & 0x100000 > 0) result = result * 0x100000000000B17217F7D1D351A389D40 >> 128; if (x & 0x80000 > 0) result = result * 0x10000000000058B90BFBE8E8B2D3D4EDE >> 128; if (x & 0x40000 > 0) result = result * 0x1000000000002C5C85FDF4741BEA6E77E >> 128; if (x & 0x20000 > 0) result = result * 0x100000000000162E42FEFA39FE95583C2 >> 128; if (x & 0x10000 > 0) result = result * 0x1000000000000B17217F7D1CFB72B45E1 >> 128; if (x & 0x8000 > 0) result = result * 0x100000000000058B90BFBE8E7CC35C3F0 >> 128; if (x & 0x4000 > 0) result = result * 0x10000000000002C5C85FDF473E242EA38 >> 128; if (x & 0x2000 > 0) result = result * 0x1000000000000162E42FEFA39F02B772C >> 128; if (x & 0x1000 > 0) result = result * 0x10000000000000B17217F7D1CF7D83C1A >> 128; if (x & 0x800 > 0) result = result * 0x1000000000000058B90BFBE8E7BDCBE2E >> 128; if (x & 0x400 > 0) result = result * 0x100000000000002C5C85FDF473DEA871F >> 128; if (x & 0x200 > 0) result = result * 0x10000000000000162E42FEFA39EF44D91 >> 128; if (x & 0x100 > 0) result = result * 0x100000000000000B17217F7D1CF79E949 >> 128; if (x & 0x80 > 0) result = result * 0x10000000000000058B90BFBE8E7BCE544 >> 128; if (x & 0x40 > 0) result = result * 0x1000000000000002C5C85FDF473DE6ECA >> 128; if (x & 0x20 > 0) result = result * 0x100000000000000162E42FEFA39EF366F >> 128; if (x & 0x10 > 0) result = result * 0x1000000000000000B17217F7D1CF79AFA >> 128; if (x & 0x8 > 0) result = result * 0x100000000000000058B90BFBE8E7BCD6D >> 128; if (x & 0x4 > 0) result = result * 0x10000000000000002C5C85FDF473DE6B2 >> 128; if (x & 0x2 > 0) result = result * 0x1000000000000000162E42FEFA39EF358 >> 128; if (x & 0x1 > 0) result = result * 0x10000000000000000B17217F7D1CF79AB >> 128; result >>= uint256 (63 - (x >> 64)); require (result <= uint256 (MAX_64x64)); return int128 (result); } /** * Calculate natural exponent of x. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function exp (int128 x) internal pure returns (int128) { require (x < 0x400000000000000000); // Overflow if (x < -0x400000000000000000) return 0; // Underflow return exp_2 ( int128 (int256 (x) * 0x171547652B82FE1777D0FFDA0D23A7D12 >> 128)); } /** * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit * integer numbers. Revert on overflow or when y is zero. * * @param x unsigned 256-bit integer number * @param y unsigned 256-bit integer number * @return unsigned 64.64-bit fixed point number */ function divuu (uint256 x, uint256 y) private pure returns (uint128) { require (y != 0); uint256 result; if (x <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) result = (x << 64) / y; else { uint256 msb = 192; uint256 xc = x >> 192; if (xc >= 0x100000000) { xc >>= 32; msb += 32; } if (xc >= 0x10000) { xc >>= 16; msb += 16; } if (xc >= 0x100) { xc >>= 8; msb += 8; } if (xc >= 0x10) { xc >>= 4; msb += 4; } if (xc >= 0x4) { xc >>= 2; msb += 2; } if (xc >= 0x2) msb += 1; // No need to shift xc anymore result = (x << 255 - msb) / ((y - 1 >> msb - 191) + 1); require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); uint256 hi = result * (y >> 128); uint256 lo = result * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); uint256 xh = x >> 192; uint256 xl = x << 64; if (xl < lo) xh -= 1; xl -= lo; // We rely on overflow behavior here lo = hi << 128; if (xl < lo) xh -= 1; xl -= lo; // We rely on overflow behavior here assert (xh == hi >> 128); result += xl / y; } require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return uint128 (result); } /** * Calculate sqrt (x) rounding down, where x is unsigned 256-bit integer * number. * * @param x unsigned 256-bit integer number * @return unsigned 128-bit integer number */ function sqrtu (uint256 x) private pure returns (uint128) { if (x == 0) return 0; else { uint256 xx = x; uint256 r = 1; if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; } if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; } if (xx >= 0x100000000) { xx >>= 32; r <<= 16; } if (xx >= 0x10000) { xx >>= 16; r <<= 8; } if (xx >= 0x100) { xx >>= 8; r <<= 4; } if (xx >= 0x10) { xx >>= 4; r <<= 2; } if (xx >= 0x8) { r <<= 1; } r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; // Seven iterations should be enough uint256 r1 = x / r; return uint128 (r < r1 ? r : r1); } } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "./TokenHandler.sol"; import "../nTokenHandler.sol"; import "../../math/SafeInt256.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; library Incentives { using SafeMath for uint256; using SafeInt256 for int256; /// @dev Notional incentivizes nTokens using the formula: /// incentivesToClaim = (tokenBalance / totalSupply) * emissionRatePerYear * proRataYears /// where proRataYears is: /// (timeSinceLastClaim / YEAR) * INTERNAL_TOKEN_PRECISION /// @return (emissionRatePerYear * proRataYears), decimal basis is (1e8 * 1e8 = 1e16) function _getIncentiveRate(uint256 timeSinceLastClaim, uint256 emissionRatePerYear) private pure returns (uint256) { // (timeSinceLastClaim * INTERNAL_TOKEN_PRECISION) / YEAR uint256 proRataYears = timeSinceLastClaim.mul(uint256(Constants.INTERNAL_TOKEN_PRECISION)).div(Constants.YEAR); return proRataYears.mul(emissionRatePerYear); } /// @notice Calculates the claimable incentives for a particular nToken and account function calculateIncentivesToClaim( address tokenAddress, uint256 nTokenBalance, uint256 lastClaimTime, uint256 lastClaimIntegralSupply, uint256 blockTime, uint256 integralTotalSupply ) internal view returns (uint256) { if (lastClaimTime == 0 || lastClaimTime >= blockTime) return 0; // prettier-ignore ( /* currencyId */, uint256 emissionRatePerYear, /* initializedTime */, /* assetArrayLength */, /* parameters */ ) = nTokenHandler.getNTokenContext(tokenAddress); // No overflow here, checked above uint256 timeSinceLastClaim = blockTime - lastClaimTime; uint256 incentiveRate = _getIncentiveRate( timeSinceLastClaim, // Convert this to the appropriate denomination, emissionRatePerYear is denominated // in whole tokens emissionRatePerYear.mul(uint256(Constants.INTERNAL_TOKEN_PRECISION)) ); // Returns the average supply between now and the previous mint time using the integral of the total // supply. uint256 avgTotalSupply = integralTotalSupply.sub(lastClaimIntegralSupply).div(timeSinceLastClaim); if (avgTotalSupply == 0) return 0; uint256 incentivesToClaim = nTokenBalance.mul(incentiveRate).div(avgTotalSupply); // incentiveRate has a decimal basis of 1e16 so divide by token precision to reduce to 1e8 incentivesToClaim = incentivesToClaim.div(uint256(Constants.INTERNAL_TOKEN_PRECISION)); return incentivesToClaim; } /// @notice Incentives must be claimed every time nToken balance changes function claimIncentives(BalanceState memory balanceState, address account) internal returns (uint256) { uint256 blockTime = block.timestamp; address tokenAddress = nTokenHandler.nTokenAddress(balanceState.currencyId); // This will set the new supply and return the previous integral total supply uint256 integralTotalSupply = nTokenHandler.changeNTokenSupply( tokenAddress, balanceState.netNTokenSupplyChange, blockTime ); uint256 incentivesToClaim = calculateIncentivesToClaim( tokenAddress, balanceState.storedNTokenBalance.toUint(), balanceState.lastClaimTime, balanceState.lastClaimIntegralSupply, blockTime, integralTotalSupply ); balanceState.lastClaimTime = blockTime; balanceState.lastClaimIntegralSupply = integralTotalSupply; if (incentivesToClaim > 0) TokenHandler.transferIncentive(account, incentivesToClaim); return incentivesToClaim; } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../global/LibStorage.sol"; import "./balances/BalanceHandler.sol"; import "./portfolio/BitmapAssetsHandler.sol"; import "./portfolio/PortfolioHandler.sol"; library AccountContextHandler { using PortfolioHandler for PortfolioState; bytes18 private constant TURN_OFF_PORTFOLIO_FLAGS = 0x7FFF7FFF7FFF7FFF7FFF7FFF7FFF7FFF7FFF; event AccountContextUpdate(address indexed account); /// @notice Returns the account context of a given account function getAccountContext(address account) internal view returns (AccountContext memory) { mapping(address => AccountContext) storage store = LibStorage.getAccountStorage(); return store[account]; } /// @notice Sets the account context of a given account function setAccountContext(AccountContext memory accountContext, address account) internal { mapping(address => AccountContext) storage store = LibStorage.getAccountStorage(); store[account] = accountContext; emit AccountContextUpdate(account); } function isBitmapEnabled(AccountContext memory accountContext) internal pure returns (bool) { return accountContext.bitmapCurrencyId != 0; } /// @notice Sets the account context of a given account function enableBitmapForAccount( AccountContext memory accountContext, address account, uint16 currencyId, uint256 blockTime ) internal view { // Allow setting the currency id to zero to turn off bitmap require(currencyId <= Constants.MAX_CURRENCIES, "AC: invalid currency id"); if (isBitmapEnabled(accountContext)) { // Account cannot change their bitmap if they have assets set bytes32 ifCashBitmap = BitmapAssetsHandler.getAssetsBitmap(account, accountContext.bitmapCurrencyId); require(ifCashBitmap == 0, "AC: cannot have assets"); } else { require(accountContext.assetArrayLength == 0, "AC: cannot have assets"); // Account context also cannot have negative cash debts require(accountContext.hasDebt == 0x00, "AC: cannot have debt"); // Ensure that the active currency is set to false in the array so that there is no double // counting during FreeCollateral setActiveCurrency(accountContext, currencyId, false, Constants.ACTIVE_IN_BALANCES); } accountContext.bitmapCurrencyId = currencyId; // Setting this is required to initialize the assets bitmap uint256 nextSettleTime = DateTime.getTimeUTC0(blockTime); require(nextSettleTime < type(uint40).max); // dev: blockTime overflow accountContext.nextSettleTime = uint40(nextSettleTime); } /// @notice Returns true if the context needs to settle function mustSettleAssets(AccountContext memory accountContext) internal view returns (bool) { uint256 blockTime = block.timestamp; if (isBitmapEnabled(accountContext)) { // nextSettleTime will be set to utc0 after settlement so we // settle if this is strictly less than utc0 return accountContext.nextSettleTime < DateTime.getTimeUTC0(blockTime); } else { // 0 value occurs on an uninitialized account // Assets mature exactly on the blockTime (not one second past) so in this // case we settle on the block timestamp return 0 < accountContext.nextSettleTime && accountContext.nextSettleTime <= blockTime; } } /// @notice Checks if a currency id (uint16 max) is in the 9 slots in the account /// context active currencies list. /// @dev NOTE: this may be more efficient as a binary search since we know that the array /// is sorted function isActiveInBalances(AccountContext memory accountContext, uint256 currencyId) internal pure returns (bool) { require(currencyId != 0 && currencyId <= Constants.MAX_CURRENCIES); // dev: invalid currency id bytes18 currencies = accountContext.activeCurrencies; if (accountContext.bitmapCurrencyId == currencyId) return true; while (currencies != 0x00) { uint256 cid = uint16(bytes2(currencies) & Constants.UNMASK_FLAGS); if (cid == currencyId) { // Currency found, return if it is active in balances or not return bytes2(currencies) & Constants.ACTIVE_IN_BALANCES == Constants.ACTIVE_IN_BALANCES; } currencies = currencies << 16; } return false; } /// @notice Iterates through the active currency list and removes, inserts or does nothing /// to ensure that the active currency list is an ordered byte array of uint16 currency ids /// that refer to the currencies that an account is active in. /// /// This is called to ensure that currencies are active when the account has a non zero cash balance, /// a non zero nToken balance or a portfolio asset. function setActiveCurrency( AccountContext memory accountContext, uint256 currencyId, bool isActive, bytes2 flags ) internal pure { require(0 < currencyId && currencyId <= Constants.MAX_CURRENCIES); // dev: invalid currency id // If the bitmapped currency is already set then return here. Turning off the bitmap currency // id requires other logical handling so we will do it elsewhere. if (isActive && accountContext.bitmapCurrencyId == currencyId) return; bytes18 prefix; bytes18 suffix = accountContext.activeCurrencies; uint256 shifts; /// There are six possible outcomes from this search: /// 1. The currency id is in the list /// - it must be set to active, do nothing /// - it must be set to inactive, shift suffix and concatenate /// 2. The current id is greater than the one in the search: /// - it must be set to active, append to prefix and then concatenate the suffix, /// ensure that we do not lose the last 2 bytes if set. /// - it must be set to inactive, it is not in the list, do nothing /// 3. Reached the end of the list: /// - it must be set to active, check that the last two bytes are not set and then /// append to the prefix /// - it must be set to inactive, do nothing while (suffix != 0x00) { uint256 cid = uint256(uint16(bytes2(suffix) & Constants.UNMASK_FLAGS)); // if matches and isActive then return, already in list if (cid == currencyId && isActive) { // set flag and return accountContext.activeCurrencies = accountContext.activeCurrencies | (bytes18(flags) >> (shifts * 16)); return; } // if matches and not active then shift suffix to remove if (cid == currencyId && !isActive) { // turn off flag, if both flags are off then remove suffix = suffix & ~bytes18(flags); if (bytes2(suffix) & ~Constants.UNMASK_FLAGS == 0x0000) suffix = suffix << 16; accountContext.activeCurrencies = prefix | (suffix >> (shifts * 16)); return; } // if greater than and isActive then insert into prefix if (cid > currencyId && isActive) { prefix = prefix | (bytes18(bytes2(uint16(currencyId)) | flags) >> (shifts * 16)); // check that the total length is not greater than 9, meaning that the last // two bytes of the active currencies array should be zero require((accountContext.activeCurrencies << 128) == 0x00); // dev: AC: too many currencies // append the suffix accountContext.activeCurrencies = prefix | (suffix >> ((shifts + 1) * 16)); return; } // if past the point of the currency id and not active, not in list if (cid > currencyId && !isActive) return; prefix = prefix | (bytes18(bytes2(suffix)) >> (shifts * 16)); suffix = suffix << 16; shifts += 1; } // If reached this point and not active then return if (!isActive) return; // if end and isActive then insert into suffix, check max length require(shifts < 9); // dev: AC: too many currencies accountContext.activeCurrencies = prefix | (bytes18(bytes2(uint16(currencyId)) | flags) >> (shifts * 16)); } function _clearPortfolioActiveFlags(bytes18 activeCurrencies) internal pure returns (bytes18) { bytes18 result; // This is required to clear the suffix as we append below bytes18 suffix = activeCurrencies & TURN_OFF_PORTFOLIO_FLAGS; uint256 shifts; // This loop will append all currencies that are active in balances into the result. while (suffix != 0x00) { if (bytes2(suffix) & Constants.ACTIVE_IN_BALANCES == Constants.ACTIVE_IN_BALANCES) { // If any flags are active, then append. result = result | (bytes18(bytes2(suffix)) >> shifts); shifts += 16; } suffix = suffix << 16; } return result; } /// @notice Stores a portfolio array and updates the account context information, this method should /// be used whenever updating a portfolio array except in the case of nTokens function storeAssetsAndUpdateContext( AccountContext memory accountContext, address account, PortfolioState memory portfolioState, bool isLiquidation ) internal { // Each of these parameters is recalculated based on the entire array of assets in store assets, // regardless of whether or not they have been updated. (bool hasDebt, bytes32 portfolioCurrencies, uint8 assetArrayLength, uint40 nextSettleTime) = portfolioState.storeAssets(account); accountContext.nextSettleTime = nextSettleTime; require(mustSettleAssets(accountContext) == false); // dev: cannot store matured assets accountContext.assetArrayLength = assetArrayLength; // During liquidation it is possible for an array to go over the max amount of assets allowed due to // liquidity tokens being withdrawn into fCash. if (!isLiquidation) { require(assetArrayLength <= uint8(Constants.MAX_TRADED_MARKET_INDEX)); // dev: max assets allowed } // Sets the hasDebt flag properly based on whether or not portfolio has asset debt, meaning // a negative fCash balance. if (hasDebt) { accountContext.hasDebt = accountContext.hasDebt | Constants.HAS_ASSET_DEBT; } else { // Turns off the ASSET_DEBT flag accountContext.hasDebt = accountContext.hasDebt & ~Constants.HAS_ASSET_DEBT; } // Clear the active portfolio active flags and they will be recalculated in the next step accountContext.activeCurrencies = _clearPortfolioActiveFlags(accountContext.activeCurrencies); uint256 lastCurrency; while (portfolioCurrencies != 0) { // Portfolio currencies will not have flags, it is just an byte array of all the currencies found // in a portfolio. They are appended in a sorted order so we can compare to the previous currency // and only set it if they are different. uint256 currencyId = uint16(bytes2(portfolioCurrencies)); if (currencyId != lastCurrency) { setActiveCurrency(accountContext, currencyId, true, Constants.ACTIVE_IN_PORTFOLIO); } lastCurrency = currencyId; portfolioCurrencies = portfolioCurrencies << 16; } } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; import "./Bitmap.sol"; /** * Packs an uint value into a "floating point" storage slot. Used for storing * lastClaimIntegralSupply values in balance storage. For these values, we don't need * to maintain exact precision but we don't want to be limited by storage size overflows. * * A floating point value is defined by the 48 most significant bits and an 8 bit number * of bit shifts required to restore its precision. The unpacked value will always be less * than the packed value with a maximum absolute loss of precision of (2 ** bitShift) - 1. */ library FloatingPoint56 { function packTo56Bits(uint256 value) internal pure returns (uint56) { uint256 bitShift; // If the value is over the uint48 max value then we will shift it down // given the index of the most significant bit. We store this bit shift // in the least significant byte of the 56 bit slot available. if (value > type(uint48).max) bitShift = (Bitmap.getMSB(value) - 47); uint256 shiftedValue = value >> bitShift; return uint56((shiftedValue << 8) | bitShift); } function unpackFrom56Bits(uint256 value) internal pure returns (uint256) { // The least significant 8 bits will be the amount to bit shift uint256 bitShift = uint256(uint8(value)); return ((value >> 8) << bitShift); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../../global/Types.sol"; import "../../global/Constants.sol"; import "../markets/CashGroup.sol"; import "../markets/AssetRate.sol"; import "../portfolio/PortfolioHandler.sol"; import "../../math/SafeInt256.sol"; import "../../math/ABDKMath64x64.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; library AssetHandler { using SafeMath for uint256; using SafeInt256 for int256; using CashGroup for CashGroupParameters; using AssetRate for AssetRateParameters; function isLiquidityToken(uint256 assetType) internal pure returns (bool) { return assetType >= Constants.MIN_LIQUIDITY_TOKEN_INDEX && assetType <= Constants.MAX_LIQUIDITY_TOKEN_INDEX; } /// @notice Liquidity tokens settle every 90 days (not at the designated maturity). This method /// calculates the settlement date for any PortfolioAsset. function getSettlementDate(PortfolioAsset memory asset) internal pure returns (uint256) { require(asset.assetType > 0 && asset.assetType <= Constants.MAX_LIQUIDITY_TOKEN_INDEX); // dev: settlement date invalid asset type // 3 month tokens and fCash tokens settle at maturity if (asset.assetType <= Constants.MIN_LIQUIDITY_TOKEN_INDEX) return asset.maturity; uint256 marketLength = DateTime.getTradedMarket(asset.assetType - 1); // Liquidity tokens settle at tRef + 90 days. The formula to get a maturity is: // maturity = tRef + marketLength // Here we calculate: // tRef = (maturity - marketLength) + 90 days return asset.maturity.sub(marketLength).add(Constants.QUARTER); } /// @notice Returns the continuously compounded discount rate given an oracle rate and a time to maturity. /// The formula is: e^(-rate * timeToMaturity). function getDiscountFactor(uint256 timeToMaturity, uint256 oracleRate) internal pure returns (int256) { int128 expValue = ABDKMath64x64.fromUInt(oracleRate.mul(timeToMaturity).div(Constants.IMPLIED_RATE_TIME)); expValue = ABDKMath64x64.div(expValue, Constants.RATE_PRECISION_64x64); expValue = ABDKMath64x64.exp(ABDKMath64x64.neg(expValue)); expValue = ABDKMath64x64.mul(expValue, Constants.RATE_PRECISION_64x64); int256 discountFactor = ABDKMath64x64.toInt(expValue); return discountFactor; } /// @notice Present value of an fCash asset without any risk adjustments. function getPresentfCashValue( int256 notional, uint256 maturity, uint256 blockTime, uint256 oracleRate ) internal pure returns (int256) { if (notional == 0) return 0; // NOTE: this will revert if maturity < blockTime. That is the correct behavior because we cannot // discount matured assets. uint256 timeToMaturity = maturity.sub(blockTime); int256 discountFactor = getDiscountFactor(timeToMaturity, oracleRate); require(discountFactor <= Constants.RATE_PRECISION); // dev: get present value invalid discount factor return notional.mulInRatePrecision(discountFactor); } /// @notice Present value of an fCash asset with risk adjustments. Positive fCash value will be discounted more /// heavily than the oracle rate given and vice versa for negative fCash. function getRiskAdjustedPresentfCashValue( CashGroupParameters memory cashGroup, int256 notional, uint256 maturity, uint256 blockTime, uint256 oracleRate ) internal pure returns (int256) { if (notional == 0) return 0; // NOTE: this will revert if maturity < blockTime. That is the correct behavior because we cannot // discount matured assets. uint256 timeToMaturity = maturity.sub(blockTime); int256 discountFactor; if (notional > 0) { // If fCash is positive then discounting by a higher rate will result in a smaller // discount factor (e ^ -x), meaning a lower positive fCash value. discountFactor = getDiscountFactor( timeToMaturity, oracleRate.add(cashGroup.getfCashHaircut()) ); } else { uint256 debtBuffer = cashGroup.getDebtBuffer(); // If the adjustment exceeds the oracle rate we floor the value of the fCash // at the notional value. We don't want to require the account to hold more than // absolutely required. if (debtBuffer >= oracleRate) return notional; discountFactor = getDiscountFactor(timeToMaturity, oracleRate - debtBuffer); } require(discountFactor <= Constants.RATE_PRECISION); // dev: get risk adjusted pv, invalid discount factor return notional.mulInRatePrecision(discountFactor); } /// @notice Returns the non haircut claims on cash and fCash by the liquidity token. function getCashClaims(PortfolioAsset memory token, MarketParameters memory market) internal pure returns (int256 assetCash, int256 fCash) { require(isLiquidityToken(token.assetType) && token.notional >= 0); // dev: invalid asset, get cash claims assetCash = market.totalAssetCash.mul(token.notional).div(market.totalLiquidity); fCash = market.totalfCash.mul(token.notional).div(market.totalLiquidity); } /// @notice Returns the haircut claims on cash and fCash function getHaircutCashClaims( PortfolioAsset memory token, MarketParameters memory market, CashGroupParameters memory cashGroup ) internal pure returns (int256 assetCash, int256 fCash) { require(isLiquidityToken(token.assetType) && token.notional >= 0); // dev: invalid asset get haircut cash claims require(token.currencyId == cashGroup.currencyId); // dev: haircut cash claims, currency id mismatch // This won't overflow, the liquidity token haircut is stored as an uint8 int256 haircut = int256(cashGroup.getLiquidityHaircut(token.assetType)); assetCash = _calcToken(market.totalAssetCash, token.notional, haircut, market.totalLiquidity); fCash = _calcToken(market.totalfCash, token.notional, haircut, market.totalLiquidity); return (assetCash, fCash); } /// @dev This is here to clean up the stack in getHaircutCashClaims function _calcToken( int256 numerator, int256 tokens, int256 haircut, int256 liquidity ) private pure returns (int256) { return numerator.mul(tokens).mul(haircut).div(Constants.PERCENTAGE_DECIMALS).div(liquidity); } /// @notice Returns the asset cash claim and the present value of the fCash asset (if it exists) function getLiquidityTokenValue( uint256 index, CashGroupParameters memory cashGroup, MarketParameters memory market, PortfolioAsset[] memory assets, uint256 blockTime, bool riskAdjusted ) internal view returns (int256, int256) { PortfolioAsset memory liquidityToken = assets[index]; { (uint256 marketIndex, bool idiosyncratic) = DateTime.getMarketIndex( cashGroup.maxMarketIndex, liquidityToken.maturity, blockTime ); // Liquidity tokens can never be idiosyncratic require(!idiosyncratic); // dev: idiosyncratic liquidity token // This market will always be initialized, if a liquidity token exists that means the // market has some liquidity in it. cashGroup.loadMarket(market, marketIndex, true, blockTime); } int256 assetCashClaim; int256 fCashClaim; if (riskAdjusted) { (assetCashClaim, fCashClaim) = getHaircutCashClaims(liquidityToken, market, cashGroup); } else { (assetCashClaim, fCashClaim) = getCashClaims(liquidityToken, market); } // Find the matching fCash asset and net off the value, assumes that the portfolio is sorted and // in that case we know the previous asset will be the matching fCash asset if (index > 0) { PortfolioAsset memory maybefCash = assets[index - 1]; if ( maybefCash.assetType == Constants.FCASH_ASSET_TYPE && maybefCash.currencyId == liquidityToken.currencyId && maybefCash.maturity == liquidityToken.maturity ) { // Net off the fCashClaim here and we will discount it to present value in the second pass. // WARNING: this modifies the portfolio in memory and therefore we cannot store this portfolio! maybefCash.notional = maybefCash.notional.add(fCashClaim); // This state will prevent the fCash asset from being stored. maybefCash.storageState = AssetStorageState.RevertIfStored; return (assetCashClaim, 0); } } // If not matching fCash asset found then get the pv directly if (riskAdjusted) { int256 pv = getRiskAdjustedPresentfCashValue( cashGroup, fCashClaim, liquidityToken.maturity, blockTime, market.oracleRate ); return (assetCashClaim, pv); } else { int256 pv = getPresentfCashValue(fCashClaim, liquidityToken.maturity, blockTime, market.oracleRate); return (assetCashClaim, pv); } } /// @notice Returns present value of all assets in the cash group as asset cash and the updated /// portfolio index where the function has ended. /// @return the value of the cash group in asset cash function getNetCashGroupValue( PortfolioAsset[] memory assets, CashGroupParameters memory cashGroup, MarketParameters memory market, uint256 blockTime, uint256 portfolioIndex ) internal view returns (int256, uint256) { int256 presentValueAsset; int256 presentValueUnderlying; // First calculate value of liquidity tokens because we need to net off fCash value // before discounting to present value for (uint256 i = portfolioIndex; i < assets.length; i++) { if (!isLiquidityToken(assets[i].assetType)) continue; if (assets[i].currencyId != cashGroup.currencyId) break; (int256 assetCashClaim, int256 pv) = getLiquidityTokenValue( i, cashGroup, market, assets, blockTime, true // risk adjusted ); presentValueAsset = presentValueAsset.add(assetCashClaim); presentValueUnderlying = presentValueUnderlying.add(pv); } uint256 j = portfolioIndex; for (; j < assets.length; j++) { PortfolioAsset memory a = assets[j]; if (a.assetType != Constants.FCASH_ASSET_TYPE) continue; // If we hit a different currency id then we've accounted for all assets in this currency // j will mark the index where we don't have this currency anymore if (a.currencyId != cashGroup.currencyId) break; uint256 oracleRate = cashGroup.calculateOracleRate(a.maturity, blockTime); int256 pv = getRiskAdjustedPresentfCashValue( cashGroup, a.notional, a.maturity, blockTime, oracleRate ); presentValueUnderlying = presentValueUnderlying.add(pv); } presentValueAsset = presentValueAsset.add( cashGroup.assetRate.convertFromUnderlying(presentValueUnderlying) ); return (presentValueAsset, j); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../AccountContextHandler.sol"; import "../markets/CashGroup.sol"; import "../valuation/AssetHandler.sol"; import "../../math/Bitmap.sol"; import "../../math/SafeInt256.sol"; import "../../global/LibStorage.sol"; import "../../global/Constants.sol"; import "../../global/Types.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; library BitmapAssetsHandler { using SafeMath for uint256; using SafeInt256 for int256; using Bitmap for bytes32; using CashGroup for CashGroupParameters; using AccountContextHandler for AccountContext; function getAssetsBitmap(address account, uint256 currencyId) internal view returns (bytes32 assetsBitmap) { mapping(address => mapping(uint256 => bytes32)) storage store = LibStorage.getAssetsBitmapStorage(); return store[account][currencyId]; } function setAssetsBitmap( address account, uint256 currencyId, bytes32 assetsBitmap ) internal { require(assetsBitmap.totalBitsSet() <= Constants.MAX_BITMAP_ASSETS, "Over max assets"); mapping(address => mapping(uint256 => bytes32)) storage store = LibStorage.getAssetsBitmapStorage(); store[account][currencyId] = assetsBitmap; } function getifCashNotional( address account, uint256 currencyId, uint256 maturity ) internal view returns (int256 notional) { mapping(address => mapping(uint256 => mapping(uint256 => ifCashStorage))) storage store = LibStorage.getifCashBitmapStorage(); return store[account][currencyId][maturity].notional; } /// @notice Adds multiple assets to a bitmap portfolio function addMultipleifCashAssets( address account, AccountContext memory accountContext, PortfolioAsset[] memory assets ) internal { require(accountContext.isBitmapEnabled()); // dev: bitmap currency not set uint256 currencyId = accountContext.bitmapCurrencyId; for (uint256 i; i < assets.length; i++) { PortfolioAsset memory asset = assets[i]; if (asset.notional == 0) continue; require(asset.currencyId == currencyId); // dev: invalid asset in set ifcash assets require(asset.assetType == Constants.FCASH_ASSET_TYPE); // dev: invalid asset in set ifcash assets int256 finalNotional; finalNotional = addifCashAsset( account, currencyId, asset.maturity, accountContext.nextSettleTime, asset.notional ); if (finalNotional < 0) accountContext.hasDebt = accountContext.hasDebt | Constants.HAS_ASSET_DEBT; } } /// @notice Add an ifCash asset in the bitmap and mapping. Updates the bitmap in memory /// but not in storage. /// @return the updated assets bitmap and the final notional amount function addifCashAsset( address account, uint256 currencyId, uint256 maturity, uint256 nextSettleTime, int256 notional ) internal returns (int256) { bytes32 assetsBitmap = getAssetsBitmap(account, currencyId); mapping(address => mapping(uint256 => mapping(uint256 => ifCashStorage))) storage store = LibStorage.getifCashBitmapStorage(); ifCashStorage storage fCashSlot = store[account][currencyId][maturity]; (uint256 bitNum, bool isExact) = DateTime.getBitNumFromMaturity(nextSettleTime, maturity); require(isExact); // dev: invalid maturity in set ifcash asset if (assetsBitmap.isBitSet(bitNum)) { // Bit is set so we read and update the notional amount int256 finalNotional = notional.add(fCashSlot.notional); require(type(int128).min <= finalNotional && finalNotional <= type(int128).max); // dev: bitmap notional overflow fCashSlot.notional = int128(finalNotional); // If the new notional is zero then turn off the bit if (finalNotional == 0) { assetsBitmap = assetsBitmap.setBit(bitNum, false); } setAssetsBitmap(account, currencyId, assetsBitmap); return finalNotional; } if (notional != 0) { // Bit is not set so we turn it on and update the mapping directly, no read required. require(type(int128).min <= notional && notional <= type(int128).max); // dev: bitmap notional overflow fCashSlot.notional = int128(notional); assetsBitmap = assetsBitmap.setBit(bitNum, true); setAssetsBitmap(account, currencyId, assetsBitmap); } return notional; } /// @notice Returns the present value of an asset function _getPresentValue( address account, uint256 currencyId, uint256 maturity, uint256 blockTime, CashGroupParameters memory cashGroup, bool riskAdjusted ) private view returns (int256) { int256 notional = getifCashNotional(account, currencyId, maturity); // In this case the asset has matured and the total value is just the notional amount if (maturity <= blockTime) { return notional; } else { uint256 oracleRate = cashGroup.calculateOracleRate(maturity, blockTime); if (riskAdjusted) { return AssetHandler.getRiskAdjustedPresentfCashValue( cashGroup, notional, maturity, blockTime, oracleRate ); } else { return AssetHandler.getPresentfCashValue( notional, maturity, blockTime, oracleRate ); } } } /// @notice Get the net present value of all the ifCash assets function getifCashNetPresentValue( address account, uint256 currencyId, uint256 nextSettleTime, uint256 blockTime, CashGroupParameters memory cashGroup, bool riskAdjusted ) internal view returns (int256 totalValueUnderlying, bool hasDebt) { bytes32 assetsBitmap = getAssetsBitmap(account, currencyId); uint256 bitNum = assetsBitmap.getNextBitNum(); while (bitNum != 0) { uint256 maturity = DateTime.getMaturityFromBitNum(nextSettleTime, bitNum); int256 pv = _getPresentValue( account, currencyId, maturity, blockTime, cashGroup, riskAdjusted ); totalValueUnderlying = totalValueUnderlying.add(pv); if (pv < 0) hasDebt = true; // Turn off the bit and look for the next one assetsBitmap = assetsBitmap.setBit(bitNum, false); bitNum = assetsBitmap.getNextBitNum(); } } /// @notice Returns the ifCash assets as an array function getifCashArray( address account, uint256 currencyId, uint256 nextSettleTime ) internal view returns (PortfolioAsset[] memory) { bytes32 assetsBitmap = getAssetsBitmap(account, currencyId); uint256 index = assetsBitmap.totalBitsSet(); PortfolioAsset[] memory assets = new PortfolioAsset[](index); index = 0; uint256 bitNum = assetsBitmap.getNextBitNum(); while (bitNum != 0) { uint256 maturity = DateTime.getMaturityFromBitNum(nextSettleTime, bitNum); int256 notional = getifCashNotional(account, currencyId, maturity); PortfolioAsset memory asset = assets[index]; asset.currencyId = currencyId; asset.maturity = maturity; asset.assetType = Constants.FCASH_ASSET_TYPE; asset.notional = notional; index += 1; // Turn off the bit and look for the next one assetsBitmap = assetsBitmap.setBit(bitNum, false); bitNum = assetsBitmap.getNextBitNum(); } return assets; } /// @notice Used to reduce an nToken ifCash assets portfolio proportionately when redeeming /// nTokens to its underlying assets. function reduceifCashAssetsProportional( address account, uint256 currencyId, uint256 nextSettleTime, int256 tokensToRedeem, int256 totalSupply ) internal returns (PortfolioAsset[] memory) { // It is not possible to redeem the entire token supply because some liquidity tokens must remain // in the liquidity token portfolio in order to re-initialize markets. require(tokensToRedeem < totalSupply, "Cannot redeem"); bytes32 assetsBitmap = getAssetsBitmap(account, currencyId); uint256 index = assetsBitmap.totalBitsSet(); mapping(address => mapping(uint256 => mapping(uint256 => ifCashStorage))) storage store = LibStorage.getifCashBitmapStorage(); PortfolioAsset[] memory assets = new PortfolioAsset[](index); index = 0; uint256 bitNum = assetsBitmap.getNextBitNum(); while (bitNum != 0) { uint256 maturity = DateTime.getMaturityFromBitNum(nextSettleTime, bitNum); ifCashStorage storage fCashSlot = store[account][currencyId][maturity]; int256 notional = fCashSlot.notional; int256 notionalToTransfer = notional.mul(tokensToRedeem).div(totalSupply); int256 finalNotional = notional.sub(notionalToTransfer); require(type(int128).min <= finalNotional && finalNotional <= type(int128).max); // dev: bitmap notional overflow fCashSlot.notional = int128(finalNotional); PortfolioAsset memory asset = assets[index]; asset.currencyId = currencyId; asset.maturity = maturity; asset.assetType = Constants.FCASH_ASSET_TYPE; asset.notional = notionalToTransfer; index += 1; // Turn off the bit and look for the next one assetsBitmap = assetsBitmap.setBit(bitNum, false); bitNum = assetsBitmap.getNextBitNum(); } return assets; } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "./TransferAssets.sol"; import "../valuation/AssetHandler.sol"; import "../../math/SafeInt256.sol"; /// @notice Handles the management of an array of assets including reading from storage, inserting /// updating, deleting and writing back to storage. library PortfolioHandler { using SafeInt256 for int256; using AssetHandler for PortfolioAsset; // Mirror of LibStorage.MAX_PORTFOLIO_ASSETS uint256 private constant MAX_PORTFOLIO_ASSETS = 16; /// @notice Primarily used by the TransferAssets library function addMultipleAssets(PortfolioState memory portfolioState, PortfolioAsset[] memory assets) internal pure { for (uint256 i = 0; i < assets.length; i++) { PortfolioAsset memory asset = assets[i]; if (asset.notional == 0) continue; addAsset( portfolioState, asset.currencyId, asset.maturity, asset.assetType, asset.notional ); } } function _mergeAssetIntoArray( PortfolioAsset[] memory assetArray, uint256 currencyId, uint256 maturity, uint256 assetType, int256 notional ) private pure returns (bool) { for (uint256 i = 0; i < assetArray.length; i++) { PortfolioAsset memory asset = assetArray[i]; if ( asset.assetType != assetType || asset.currencyId != currencyId || asset.maturity != maturity ) continue; // Either of these storage states mean that some error in logic has occurred, we cannot // store this portfolio require( asset.storageState != AssetStorageState.Delete && asset.storageState != AssetStorageState.RevertIfStored ); // dev: portfolio handler deleted storage int256 newNotional = asset.notional.add(notional); // Liquidity tokens cannot be reduced below zero. if (AssetHandler.isLiquidityToken(assetType)) { require(newNotional >= 0); // dev: portfolio handler negative liquidity token balance } require(newNotional >= type(int88).min && newNotional <= type(int88).max); // dev: portfolio handler notional overflow asset.notional = newNotional; asset.storageState = AssetStorageState.Update; return true; } return false; } /// @notice Adds an asset to a portfolio state in memory (does not write to storage) /// @dev Ensures that only one version of an asset exists in a portfolio (i.e. does not allow two fCash assets of the same maturity /// to exist in a single portfolio). Also ensures that liquidity tokens do not have a negative notional. function addAsset( PortfolioState memory portfolioState, uint256 currencyId, uint256 maturity, uint256 assetType, int256 notional ) internal pure { if ( // Will return true if merged _mergeAssetIntoArray( portfolioState.storedAssets, currencyId, maturity, assetType, notional ) ) return; if (portfolioState.lastNewAssetIndex > 0) { bool merged = _mergeAssetIntoArray( portfolioState.newAssets, currencyId, maturity, assetType, notional ); if (merged) return; } // At this point if we have not merged the asset then append to the array // Cannot remove liquidity that the portfolio does not have if (AssetHandler.isLiquidityToken(assetType)) { require(notional >= 0); // dev: portfolio handler negative liquidity token balance } require(notional >= type(int88).min && notional <= type(int88).max); // dev: portfolio handler notional overflow // Need to provision a new array at this point if (portfolioState.lastNewAssetIndex == portfolioState.newAssets.length) { portfolioState.newAssets = _extendNewAssetArray(portfolioState.newAssets); } // Otherwise add to the new assets array. It should not be possible to add matching assets in a single transaction, we will // check this again when we write to storage. Assigning to memory directly here, do not allocate new memory via struct. PortfolioAsset memory newAsset = portfolioState.newAssets[portfolioState.lastNewAssetIndex]; newAsset.currencyId = currencyId; newAsset.maturity = maturity; newAsset.assetType = assetType; newAsset.notional = notional; newAsset.storageState = AssetStorageState.NoChange; portfolioState.lastNewAssetIndex += 1; } /// @dev Extends the new asset array if it is not large enough, this is likely to get a bit expensive if we do /// it too much function _extendNewAssetArray(PortfolioAsset[] memory newAssets) private pure returns (PortfolioAsset[] memory) { // Double the size of the new asset array every time we have to extend to reduce the number of times // that we have to extend it. This will go: 0, 1, 2, 4, 8 (probably stops there). uint256 newLength = newAssets.length == 0 ? 1 : newAssets.length * 2; PortfolioAsset[] memory extendedArray = new PortfolioAsset[](newLength); for (uint256 i = 0; i < newAssets.length; i++) { extendedArray[i] = newAssets[i]; } return extendedArray; } /// @notice Takes a portfolio state and writes it to storage. /// @dev This method should only be called directly by the nToken. Account updates to portfolios should happen via /// the storeAssetsAndUpdateContext call in the AccountContextHandler.sol library. /// @return updated variables to update the account context with /// hasDebt: whether or not the portfolio has negative fCash assets /// portfolioActiveCurrencies: a byte32 word with all the currencies in the portfolio /// uint8: the length of the storage array /// uint40: the new nextSettleTime for the portfolio function storeAssets(PortfolioState memory portfolioState, address account) internal returns ( bool, bytes32, uint8, uint40 ) { bool hasDebt; // NOTE: cannot have more than 16 assets or this byte object will overflow. Max assets is // set to 7 and the worst case during liquidation would be 7 liquidity tokens that generate // 7 additional fCash assets for a total of 14 assets. Although even in this case all assets // would be of the same currency so it would not change the end result of the active currency // calculation. bytes32 portfolioActiveCurrencies; uint256 nextSettleTime; for (uint256 i = 0; i < portfolioState.storedAssets.length; i++) { PortfolioAsset memory asset = portfolioState.storedAssets[i]; // NOTE: this is to prevent the storage of assets that have been modified in the AssetHandler // during valuation. require(asset.storageState != AssetStorageState.RevertIfStored); // Mark any zero notional assets as deleted if (asset.storageState != AssetStorageState.Delete && asset.notional == 0) { deleteAsset(portfolioState, i); } } // First delete assets from asset storage to maintain asset storage indexes for (uint256 i = 0; i < portfolioState.storedAssets.length; i++) { PortfolioAsset memory asset = portfolioState.storedAssets[i]; if (asset.storageState == AssetStorageState.Delete) { // Delete asset from storage uint256 currentSlot = asset.storageSlot; assembly { sstore(currentSlot, 0x00) } } else { if (asset.storageState == AssetStorageState.Update) { PortfolioAssetStorage storage assetStorage; uint256 currentSlot = asset.storageSlot; assembly { assetStorage.slot := currentSlot } _storeAsset(asset, assetStorage); } // Update portfolio context for every asset that is in storage, whether it is // updated in storage or not. (hasDebt, portfolioActiveCurrencies, nextSettleTime) = _updatePortfolioContext( asset, hasDebt, portfolioActiveCurrencies, nextSettleTime ); } } // Add new assets uint256 assetStorageLength = portfolioState.storedAssetLength; mapping(address => PortfolioAssetStorage[MAX_PORTFOLIO_ASSETS]) storage store = LibStorage.getPortfolioArrayStorage(); PortfolioAssetStorage[MAX_PORTFOLIO_ASSETS] storage storageArray = store[account]; for (uint256 i = 0; i < portfolioState.newAssets.length; i++) { PortfolioAsset memory asset = portfolioState.newAssets[i]; if (asset.notional == 0) continue; require( asset.storageState != AssetStorageState.Delete && asset.storageState != AssetStorageState.RevertIfStored ); // dev: store assets deleted storage (hasDebt, portfolioActiveCurrencies, nextSettleTime) = _updatePortfolioContext( asset, hasDebt, portfolioActiveCurrencies, nextSettleTime ); _storeAsset(asset, storageArray[assetStorageLength]); assetStorageLength += 1; } // 16 is the maximum number of assets or portfolio active currencies will overflow at 32 bytes with // 2 bytes per currency require(assetStorageLength <= 16 && nextSettleTime <= type(uint40).max); // dev: portfolio return value overflow return ( hasDebt, portfolioActiveCurrencies, uint8(assetStorageLength), uint40(nextSettleTime) ); } /// @notice Updates context information during the store assets method function _updatePortfolioContext( PortfolioAsset memory asset, bool hasDebt, bytes32 portfolioActiveCurrencies, uint256 nextSettleTime ) private pure returns ( bool, bytes32, uint256 ) { uint256 settlementDate = asset.getSettlementDate(); // Tis will set it to the minimum settlement date if (nextSettleTime == 0 || nextSettleTime > settlementDate) { nextSettleTime = settlementDate; } hasDebt = hasDebt || asset.notional < 0; require(uint16(uint256(portfolioActiveCurrencies)) == 0); // dev: portfolio active currencies overflow portfolioActiveCurrencies = (portfolioActiveCurrencies >> 16) | (bytes32(asset.currencyId) << 240); return (hasDebt, portfolioActiveCurrencies, nextSettleTime); } /// @dev Encodes assets for storage function _storeAsset( PortfolioAsset memory asset, PortfolioAssetStorage storage assetStorage ) internal { require(0 < asset.currencyId && asset.currencyId <= Constants.MAX_CURRENCIES); // dev: encode asset currency id overflow require(0 < asset.maturity && asset.maturity <= type(uint40).max); // dev: encode asset maturity overflow require(0 < asset.assetType && asset.assetType <= Constants.MAX_LIQUIDITY_TOKEN_INDEX); // dev: encode asset type invalid require(type(int88).min <= asset.notional && asset.notional <= type(int88).max); // dev: encode asset notional overflow assetStorage.currencyId = uint16(asset.currencyId); assetStorage.maturity = uint40(asset.maturity); assetStorage.assetType = uint8(asset.assetType); assetStorage.notional = int88(asset.notional); } /// @notice Deletes an asset from a portfolio /// @dev This method should only be called during settlement, assets can only be removed from a portfolio before settlement /// by adding the offsetting negative position function deleteAsset(PortfolioState memory portfolioState, uint256 index) internal pure { require(index < portfolioState.storedAssets.length); // dev: stored assets bounds require(portfolioState.storedAssetLength > 0); // dev: stored assets length is zero PortfolioAsset memory assetToDelete = portfolioState.storedAssets[index]; require( assetToDelete.storageState != AssetStorageState.Delete && assetToDelete.storageState != AssetStorageState.RevertIfStored ); // dev: cannot delete asset portfolioState.storedAssetLength -= 1; uint256 maxActiveSlotIndex; uint256 maxActiveSlot; // The max active slot is the last storage slot where an asset exists, it's not clear where this will be in the // array so we search for it here. for (uint256 i; i < portfolioState.storedAssets.length; i++) { PortfolioAsset memory a = portfolioState.storedAssets[i]; if (a.storageSlot > maxActiveSlot && a.storageState != AssetStorageState.Delete) { maxActiveSlot = a.storageSlot; maxActiveSlotIndex = i; } } if (index == maxActiveSlotIndex) { // In this case we are deleting the asset with the max storage slot so no swap is necessary. assetToDelete.storageState = AssetStorageState.Delete; return; } // Swap the storage slots of the deleted asset with the last non-deleted asset in the array. Mark them accordingly // so that when we call store assets they will be updated appropriately PortfolioAsset memory assetToSwap = portfolioState.storedAssets[maxActiveSlotIndex]; ( assetToSwap.storageSlot, assetToDelete.storageSlot ) = ( assetToDelete.storageSlot, assetToSwap.storageSlot ); assetToSwap.storageState = AssetStorageState.Update; assetToDelete.storageState = AssetStorageState.Delete; } /// @notice Returns a portfolio array, will be sorted function getSortedPortfolio(address account, uint8 assetArrayLength) internal view returns (PortfolioAsset[] memory) { PortfolioAsset[] memory assets = _loadAssetArray(account, assetArrayLength); // No sorting required for length of 1 if (assets.length <= 1) return assets; _sortInPlace(assets); return assets; } /// @notice Builds a portfolio array from storage. The new assets hint parameter will /// be used to provision a new array for the new assets. This will increase gas efficiency /// so that we don't have to make copies when we extend the array. function buildPortfolioState( address account, uint8 assetArrayLength, uint256 newAssetsHint ) internal view returns (PortfolioState memory) { PortfolioState memory state; if (assetArrayLength == 0) return state; state.storedAssets = getSortedPortfolio(account, assetArrayLength); state.storedAssetLength = assetArrayLength; state.newAssets = new PortfolioAsset[](newAssetsHint); return state; } function _sortInPlace(PortfolioAsset[] memory assets) private pure { uint256 length = assets.length; uint256[] memory ids = new uint256[](length); for (uint256 k; k < length; k++) { PortfolioAsset memory asset = assets[k]; // Prepopulate the ids to calculate just once ids[k] = TransferAssets.encodeAssetId(asset.currencyId, asset.maturity, asset.assetType); } // Uses insertion sort uint256 i = 1; while (i < length) { uint256 j = i; while (j > 0 && ids[j - 1] > ids[j]) { // Swap j - 1 and j (ids[j - 1], ids[j]) = (ids[j], ids[j - 1]); (assets[j - 1], assets[j]) = (assets[j], assets[j - 1]); j--; } i++; } } function _loadAssetArray(address account, uint8 length) private view returns (PortfolioAsset[] memory) { // This will overflow the storage pointer require(length <= MAX_PORTFOLIO_ASSETS); mapping(address => PortfolioAssetStorage[MAX_PORTFOLIO_ASSETS]) storage store = LibStorage.getPortfolioArrayStorage(); PortfolioAssetStorage[MAX_PORTFOLIO_ASSETS] storage storageArray = store[account]; PortfolioAsset[] memory assets = new PortfolioAsset[](length); for (uint256 i = 0; i < length; i++) { PortfolioAssetStorage storage assetStorage = storageArray[i]; PortfolioAsset memory asset = assets[i]; uint256 slot; assembly { slot := assetStorage.slot } asset.currencyId = assetStorage.currencyId; asset.maturity = assetStorage.maturity; asset.assetType = assetStorage.assetType; asset.notional = assetStorage.notional; asset.storageSlot = slot; } return assets; } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "./PortfolioHandler.sol"; import "./BitmapAssetsHandler.sol"; import "../AccountContextHandler.sol"; import "../../external/SettleAssetsExternal.sol"; /// @notice Helper library for transferring assets from one portfolio to another library TransferAssets { using AccountContextHandler for AccountContext; using PortfolioHandler for PortfolioState; using SafeInt256 for int256; /// @notice Decodes asset ids function decodeAssetId(uint256 id) internal pure returns ( uint256 currencyId, uint256 maturity, uint256 assetType ) { assetType = uint8(id); maturity = uint40(id >> 8); currencyId = uint16(id >> 48); } /// @notice Encodes asset ids function encodeAssetId( uint256 currencyId, uint256 maturity, uint256 assetType ) internal pure returns (uint256) { require(currencyId <= Constants.MAX_CURRENCIES); require(maturity <= type(uint40).max); require(assetType <= Constants.MAX_LIQUIDITY_TOKEN_INDEX); return uint256( (bytes32(uint256(uint16(currencyId))) << 48) | (bytes32(uint256(uint40(maturity))) << 8) | bytes32(uint256(uint8(assetType))) ); } /// @dev Used to flip the sign of assets to decrement the `from` account that is sending assets function invertNotionalAmountsInPlace(PortfolioAsset[] memory assets) internal pure { for (uint256 i; i < assets.length; i++) { assets[i].notional = assets[i].notional.neg(); } } /// @dev Useful method for hiding the logic of updating an account. WARNING: the account /// context returned from this method may not be the same memory location as the account /// context provided if the account is settled. function placeAssetsInAccount( address account, AccountContext memory accountContext, PortfolioAsset[] memory assets ) internal returns (AccountContext memory) { // If an account has assets that require settlement then placing assets inside it // may cause issues. require(!accountContext.mustSettleAssets(), "Account must settle"); if (accountContext.isBitmapEnabled()) { // Adds fCash assets into the account and finalized storage BitmapAssetsHandler.addMultipleifCashAssets(account, accountContext, assets); } else { PortfolioState memory portfolioState = PortfolioHandler.buildPortfolioState( account, accountContext.assetArrayLength, assets.length ); // This will add assets in memory portfolioState.addMultipleAssets(assets); // This will store assets and update the account context in memory accountContext.storeAssetsAndUpdateContext(account, portfolioState, false); } return accountContext; } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../internal/portfolio/PortfolioHandler.sol"; import "../internal/balances/BalanceHandler.sol"; import "../internal/settlement/SettlePortfolioAssets.sol"; import "../internal/settlement/SettleBitmapAssets.sol"; import "../internal/AccountContextHandler.sol"; /// @notice External library for settling assets library SettleAssetsExternal { using PortfolioHandler for PortfolioState; using AccountContextHandler for AccountContext; event AccountSettled(address indexed account); /// @notice Settles an account, returns the new account context object after settlement. /// @dev The memory location of the account context object is not the same as the one returned. function settleAccount( address account, AccountContext memory accountContext ) external returns (AccountContext memory) { // Defensive check to ensure that this is a valid settlement require(accountContext.mustSettleAssets()); SettleAmount[] memory settleAmounts; PortfolioState memory portfolioState; if (accountContext.isBitmapEnabled()) { (int256 settledCash, uint256 blockTimeUTC0) = SettleBitmapAssets.settleBitmappedCashGroup( account, accountContext.bitmapCurrencyId, accountContext.nextSettleTime, block.timestamp ); require(blockTimeUTC0 < type(uint40).max); // dev: block time utc0 overflow accountContext.nextSettleTime = uint40(blockTimeUTC0); settleAmounts = new SettleAmount[](1); settleAmounts[0] = SettleAmount(accountContext.bitmapCurrencyId, settledCash); } else { portfolioState = PortfolioHandler.buildPortfolioState( account, accountContext.assetArrayLength, 0 ); settleAmounts = SettlePortfolioAssets.settlePortfolio(portfolioState, block.timestamp); accountContext.storeAssetsAndUpdateContext(account, portfolioState, false); } BalanceHandler.finalizeSettleAmounts(account, accountContext, settleAmounts); emit AccountSettled(account); return accountContext; } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../global/Types.sol"; import "../global/Constants.sol"; /// @notice Helper methods for bitmaps, they are big-endian and 1-indexed. library Bitmap { /// @notice Set a bit on or off in a bitmap, index is 1-indexed function setBit( bytes32 bitmap, uint256 index, bool setOn ) internal pure returns (bytes32) { require(index >= 1 && index <= 256); // dev: set bit index bounds if (setOn) { return bitmap | (Constants.MSB >> (index - 1)); } else { return bitmap & ~(Constants.MSB >> (index - 1)); } } /// @notice Check if a bit is set function isBitSet(bytes32 bitmap, uint256 index) internal pure returns (bool) { require(index >= 1 && index <= 256); // dev: set bit index bounds return ((bitmap << (index - 1)) & Constants.MSB) == Constants.MSB; } /// @notice Count the total bits set function totalBitsSet(bytes32 bitmap) internal pure returns (uint256) { uint256 x = uint256(bitmap); x = (x & 0x5555555555555555555555555555555555555555555555555555555555555555) + (x >> 1 & 0x5555555555555555555555555555555555555555555555555555555555555555); x = (x & 0x3333333333333333333333333333333333333333333333333333333333333333) + (x >> 2 & 0x3333333333333333333333333333333333333333333333333333333333333333); x = (x & 0x0707070707070707070707070707070707070707070707070707070707070707) + (x >> 4); x = (x & 0x000F000F000F000F000F000F000F000F000F000F000F000F000F000F000F000F) + (x >> 8 & 0x000F000F000F000F000F000F000F000F000F000F000F000F000F000F000F000F); x = x + (x >> 16); x = x + (x >> 32); x = x + (x >> 64); return (x & 0xFF) + (x >> 128 & 0xFF); } // Does a binary search over x to get the position of the most significant bit function getMSB(uint256 x) internal pure returns (uint256 msb) { // If x == 0 then there is no MSB and this method will return zero. That would // be the same as the return value when x == 1 (MSB is zero indexed), so instead // we have this require here to ensure that the values don't get mixed up. require(x != 0); // dev: get msb zero value if (x >= 0x100000000000000000000000000000000) { x >>= 128; msb += 128; } if (x >= 0x10000000000000000) { x >>= 64; msb += 64; } if (x >= 0x100000000) { x >>= 32; msb += 32; } if (x >= 0x10000) { x >>= 16; msb += 16; } if (x >= 0x100) { x >>= 8; msb += 8; } if (x >= 0x10) { x >>= 4; msb += 4; } if (x >= 0x4) { x >>= 2; msb += 2; } if (x >= 0x2) msb += 1; // No need to shift xc anymore } /// @dev getMSB returns a zero indexed bit number where zero is the first bit counting /// from the right (little endian). Asset Bitmaps are counted from the left (big endian) /// and one indexed. function getNextBitNum(bytes32 bitmap) internal pure returns (uint256 bitNum) { // Short circuit the search if bitmap is all zeros if (bitmap == 0x00) return 0; return 255 - getMSB(uint256(bitmap)) + 1; } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../valuation/AssetHandler.sol"; import "../markets/Market.sol"; import "../markets/AssetRate.sol"; import "../portfolio/PortfolioHandler.sol"; import "../../math/SafeInt256.sol"; import "../../global/Constants.sol"; import "../../global/Types.sol"; library SettlePortfolioAssets { using SafeInt256 for int256; using AssetRate for AssetRateParameters; using Market for MarketParameters; using PortfolioHandler for PortfolioState; using AssetHandler for PortfolioAsset; /// @dev Returns a SettleAmount array for the assets that will be settled function _getSettleAmountArray(PortfolioState memory portfolioState, uint256 blockTime) private pure returns (SettleAmount[] memory) { uint256 currenciesSettled; uint256 lastCurrencyId = 0; if (portfolioState.storedAssets.length == 0) return new SettleAmount[](0); // Loop backwards so "lastCurrencyId" will be set to the first currency in the portfolio // NOTE: if this contract is ever upgraded to Solidity 0.8+ then this i-- will underflow and cause // a revert, must wrap in an unchecked. for (uint256 i = portfolioState.storedAssets.length; (i--) > 0;) { PortfolioAsset memory asset = portfolioState.storedAssets[i]; // Assets settle on exactly blockTime if (asset.getSettlementDate() > blockTime) continue; // Assume that this is sorted by cash group and maturity, currencyId = 0 is unused so this // will work for the first asset if (lastCurrencyId != asset.currencyId) { lastCurrencyId = asset.currencyId; currenciesSettled++; } } // Actual currency ids will be set as we loop through the portfolio and settle assets SettleAmount[] memory settleAmounts = new SettleAmount[](currenciesSettled); if (currenciesSettled > 0) settleAmounts[0].currencyId = lastCurrencyId; return settleAmounts; } /// @notice Settles a portfolio array function settlePortfolio(PortfolioState memory portfolioState, uint256 blockTime) internal returns (SettleAmount[] memory) { AssetRateParameters memory settlementRate; SettleAmount[] memory settleAmounts = _getSettleAmountArray(portfolioState, blockTime); MarketParameters memory market; if (settleAmounts.length == 0) return settleAmounts; uint256 settleAmountIndex; for (uint256 i; i < portfolioState.storedAssets.length; i++) { PortfolioAsset memory asset = portfolioState.storedAssets[i]; uint256 settleDate = asset.getSettlementDate(); // Settlement date is on block time exactly if (settleDate > blockTime) continue; // On the first loop the lastCurrencyId is already set. if (settleAmounts[settleAmountIndex].currencyId != asset.currencyId) { // New currency in the portfolio settleAmountIndex += 1; settleAmounts[settleAmountIndex].currencyId = asset.currencyId; } settlementRate = AssetRate.buildSettlementRateStateful( asset.currencyId, asset.maturity, blockTime ); int256 assetCash; if (asset.assetType == Constants.FCASH_ASSET_TYPE) { assetCash = settlementRate.convertFromUnderlying(asset.notional); portfolioState.deleteAsset(i); } else if (AssetHandler.isLiquidityToken(asset.assetType)) { Market.loadSettlementMarket(market, asset.currencyId, asset.maturity, settleDate); int256 fCash; (assetCash, fCash) = market.removeLiquidity(asset.notional); // Assets mature exactly on block time if (asset.maturity > blockTime) { // If fCash has not yet matured then add it to the portfolio _settleLiquidityTokenTofCash(portfolioState, i, fCash); } else { // If asset has matured then settle fCash to asset cash assetCash = assetCash.add(settlementRate.convertFromUnderlying(fCash)); portfolioState.deleteAsset(i); } } settleAmounts[settleAmountIndex].netCashChange = settleAmounts[settleAmountIndex] .netCashChange .add(assetCash); } return settleAmounts; } /// @notice Settles a liquidity token to idiosyncratic fCash, this occurs when the maturity is still in the future function _settleLiquidityTokenTofCash( PortfolioState memory portfolioState, uint256 index, int256 fCash ) private pure { PortfolioAsset memory liquidityToken = portfolioState.storedAssets[index]; // If the liquidity token's maturity is still in the future then we change the entry to be // an idiosyncratic fCash entry with the net fCash amount. if (index != 0) { // Check to see if the previous index is the matching fCash asset, this will be the case when the // portfolio is sorted PortfolioAsset memory fCashAsset = portfolioState.storedAssets[index - 1]; if ( fCashAsset.currencyId == liquidityToken.currencyId && fCashAsset.maturity == liquidityToken.maturity && fCashAsset.assetType == Constants.FCASH_ASSET_TYPE ) { // This fCash asset has not matured if we are settling to fCash fCashAsset.notional = fCashAsset.notional.add(fCash); fCashAsset.storageState = AssetStorageState.Update; portfolioState.deleteAsset(index); } } // We are going to delete this asset anyway, convert to an fCash position liquidityToken.assetType = Constants.FCASH_ASSET_TYPE; liquidityToken.notional = fCash; liquidityToken.storageState = AssetStorageState.Update; } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../markets/AssetRate.sol"; import "../../global/LibStorage.sol"; import "../portfolio/BitmapAssetsHandler.sol"; import "../../math/SafeInt256.sol"; import "../../math/Bitmap.sol"; import "../../global/Constants.sol"; import "../../global/Types.sol"; /** * Settles a bitmap portfolio by checking for all matured fCash assets and turning them into cash * at the prevailing settlement rate. It will also update the asset bitmap to ensure that it continues * to correctly reference all actual maturities. fCash asset notional values are stored in *absolute* * time terms and bitmap bits are *relative* time terms based on the bitNumber and the stored oldSettleTime. * Remapping bits requires converting the old relative bit numbers to new relative bit numbers based on * newSettleTime and the absolute times (maturities) that the previous bitmap references. */ library SettleBitmapAssets { using SafeInt256 for int256; using AssetRate for AssetRateParameters; using Bitmap for bytes32; /// @notice Given a bitmap for a cash group and timestamps, will settle all assets /// that have matured and remap the bitmap to correspond to the current time. function settleBitmappedCashGroup( address account, uint256 currencyId, uint256 oldSettleTime, uint256 blockTime ) internal returns (int256 totalAssetCash, uint256 newSettleTime) { bytes32 bitmap = BitmapAssetsHandler.getAssetsBitmap(account, currencyId); // This newSettleTime will be set to the new `oldSettleTime`. The bits between 1 and // `lastSettleBit` (inclusive) will be shifted out of the bitmap and settled. The reason // that lastSettleBit is inclusive is that it refers to newSettleTime which always less // than the current block time. newSettleTime = DateTime.getTimeUTC0(blockTime); // If newSettleTime == oldSettleTime lastSettleBit will be zero require(newSettleTime >= oldSettleTime); // dev: new settle time before previous // Do not need to worry about validity, if newSettleTime is not on an exact bit we will settle up until // the closest maturity that is less than newSettleTime. (uint256 lastSettleBit, /* isValid */) = DateTime.getBitNumFromMaturity(oldSettleTime, newSettleTime); if (lastSettleBit == 0) return (totalAssetCash, newSettleTime); // Returns the next bit that is set in the bitmap uint256 nextBitNum = bitmap.getNextBitNum(); while (nextBitNum != 0 && nextBitNum <= lastSettleBit) { uint256 maturity = DateTime.getMaturityFromBitNum(oldSettleTime, nextBitNum); totalAssetCash = totalAssetCash.add( _settlefCashAsset(account, currencyId, maturity, blockTime) ); // Turn the bit off now that it is settled bitmap = bitmap.setBit(nextBitNum, false); nextBitNum = bitmap.getNextBitNum(); } bytes32 newBitmap; while (nextBitNum != 0) { uint256 maturity = DateTime.getMaturityFromBitNum(oldSettleTime, nextBitNum); (uint256 newBitNum, bool isValid) = DateTime.getBitNumFromMaturity(newSettleTime, maturity); require(isValid); // dev: invalid new bit num newBitmap = newBitmap.setBit(newBitNum, true); // Turn the bit off now that it is remapped bitmap = bitmap.setBit(nextBitNum, false); nextBitNum = bitmap.getNextBitNum(); } BitmapAssetsHandler.setAssetsBitmap(account, currencyId, newBitmap); } /// @dev Stateful settlement function to settle a bitmapped asset. Deletes the /// asset from storage after calculating it. function _settlefCashAsset( address account, uint256 currencyId, uint256 maturity, uint256 blockTime ) private returns (int256 assetCash) { mapping(address => mapping(uint256 => mapping(uint256 => ifCashStorage))) storage store = LibStorage.getifCashBitmapStorage(); int256 notional = store[account][currencyId][maturity].notional; // Gets the current settlement rate or will store a new settlement rate if it does not // yet exist. AssetRateParameters memory rate = AssetRate.buildSettlementRateStateful(currencyId, maturity, blockTime); assetCash = rate.convertFromUnderlying(notional); delete store[account][currencyId][maturity]; return assetCash; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "@openzeppelin/contracts/utils/Address.sol"; import "../utils/StorageSlot.sol"; /** * @dev This abstract contract provides getters and event emitting update functions for * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots. * * _Available since v4.1._ * */ abstract contract ERC1967Upgrade { // This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1 bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143; /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; /** * @dev Emitted when the implementation is upgraded. */ event Upgraded(address indexed implementation); /** * @dev Returns the current implementation address. */ function _getImplementation() internal view returns (address) { return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value; } /** * @dev Stores a new address in the EIP1967 implementation slot. */ function _setImplementation(address newImplementation) private { require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract"); StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; } /** * @dev Perform implementation upgrade * * Emits an {Upgraded} event. */ function _upgradeTo(address newImplementation) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Perform implementation upgrade with additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCall( address newImplementation, bytes memory data, bool forceCall ) internal { _upgradeTo(newImplementation); if (data.length > 0 || forceCall) { Address.functionDelegateCall(newImplementation, data); } } /** * @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCallSecure( address newImplementation, bytes memory data, bool forceCall ) internal { address oldImplementation = _getImplementation(); // Initial upgrade and setup call _setImplementation(newImplementation); if (data.length > 0 || forceCall) { Address.functionDelegateCall(newImplementation, data); } // Perform rollback test if not already in progress StorageSlot.BooleanSlot storage rollbackTesting = StorageSlot.getBooleanSlot(_ROLLBACK_SLOT); if (!rollbackTesting.value) { // Trigger rollback using upgradeTo from the new implementation rollbackTesting.value = true; Address.functionDelegateCall( newImplementation, abi.encodeWithSignature("upgradeTo(address)", oldImplementation) ); rollbackTesting.value = false; // Check rollback was effective require(oldImplementation == _getImplementation(), "ERC1967Upgrade: upgrade breaks further upgrades"); // Finally reset to the new implementation and log the upgrade _upgradeTo(newImplementation); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.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 } } }
Max positive value for a ABDK64x64 integer
library Market { using SafeMath for uint256; using SafeInt256 for int256; using CashGroup for CashGroupParameters; using AssetRate for AssetRateParameters; int256 private constant MAX64 = 0x7FFFFFFFFFFFFFFF; function addLiquidity(MarketParameters memory market, int256 assetCash) internal returns (int256 liquidityTokens, int256 fCash) } pragma solidity ^0.7.0; { require(market.totalLiquidity > 0, "M: zero liquidity"); if (assetCash == 0) return (0, 0); liquidityTokens = market.totalLiquidity.mul(assetCash).div(market.totalAssetCash); fCash = market.totalfCash.mul(assetCash).div(market.totalAssetCash); market.totalLiquidity = market.totalLiquidity.add(liquidityTokens); market.totalfCash = market.totalfCash.add(fCash); market.totalAssetCash = market.totalAssetCash.add(assetCash); _setMarketStorageForLiquidity(market); fCash = fCash.neg(); } function removeLiquidity(MarketParameters memory market, int256 tokensToRemove) internal returns (int256 assetCash, int256 fCash) { if (tokensToRemove == 0) return (0, 0); assetCash = market.totalAssetCash.mul(tokensToRemove).div(market.totalLiquidity); fCash = market.totalfCash.mul(tokensToRemove).div(market.totalLiquidity); market.totalLiquidity = market.totalLiquidity.subNoNeg(tokensToRemove); market.totalfCash = market.totalfCash.subNoNeg(fCash); market.totalAssetCash = market.totalAssetCash.subNoNeg(assetCash); _setMarketStorageForLiquidity(market); } function executeTrade( MarketParameters memory market, CashGroupParameters memory cashGroup, int256 fCashToAccount, uint256 timeToMaturity, uint256 marketIndex ) internal returns (int256 netAssetCash) { int256 netAssetCashToReserve; (netAssetCash, netAssetCashToReserve) = calculateTrade( market, cashGroup, fCashToAccount, timeToMaturity, marketIndex ); MarketStorage storage marketStorage = _getMarketStoragePointer(market); _setMarketStorage( marketStorage, market.totalfCash, market.totalAssetCash, market.lastImpliedRate, market.oracleRate, market.previousTradeTime ); BalanceHandler.incrementFeeToReserve(cashGroup.currencyId, netAssetCashToReserve); } function calculateTrade( MarketParameters memory market, CashGroupParameters memory cashGroup, int256 fCashToAccount, uint256 timeToMaturity, uint256 marketIndex ) internal view returns (int256, int256) { if (market.totalfCash <= fCashToAccount) return (0, 0); (int256 rateScalar, int256 totalCashUnderlying, int256 rateAnchor) = getExchangeRateFactors(market, cashGroup, timeToMaturity, marketIndex); int256 preFeeExchangeRate; { bool success; (preFeeExchangeRate, success) = _getExchangeRate( market.totalfCash, totalCashUnderlying, rateScalar, rateAnchor, fCashToAccount ); if (!success) return (0, 0); } _getNetCashAmountsUnderlying( cashGroup, preFeeExchangeRate, fCashToAccount, timeToMaturity ); { market.totalfCash = market.totalfCash.subNoNeg(fCashToAccount); market.lastImpliedRate = getImpliedRate( market.totalfCash, totalCashUnderlying.add(netCashToMarket), rateScalar, rateAnchor, timeToMaturity ); if (market.lastImpliedRate == 0) return (0, 0); } return _setNewMarketState( market, cashGroup.assetRate, netCashToAccount, netCashToMarket, netCashToReserve ); } function calculateTrade( MarketParameters memory market, CashGroupParameters memory cashGroup, int256 fCashToAccount, uint256 timeToMaturity, uint256 marketIndex ) internal view returns (int256, int256) { if (market.totalfCash <= fCashToAccount) return (0, 0); (int256 rateScalar, int256 totalCashUnderlying, int256 rateAnchor) = getExchangeRateFactors(market, cashGroup, timeToMaturity, marketIndex); int256 preFeeExchangeRate; { bool success; (preFeeExchangeRate, success) = _getExchangeRate( market.totalfCash, totalCashUnderlying, rateScalar, rateAnchor, fCashToAccount ); if (!success) return (0, 0); } _getNetCashAmountsUnderlying( cashGroup, preFeeExchangeRate, fCashToAccount, timeToMaturity ); { market.totalfCash = market.totalfCash.subNoNeg(fCashToAccount); market.lastImpliedRate = getImpliedRate( market.totalfCash, totalCashUnderlying.add(netCashToMarket), rateScalar, rateAnchor, timeToMaturity ); if (market.lastImpliedRate == 0) return (0, 0); } return _setNewMarketState( market, cashGroup.assetRate, netCashToAccount, netCashToMarket, netCashToReserve ); } (int256 netCashToAccount, int256 netCashToMarket, int256 netCashToReserve) = if (netCashToAccount == 0) return (0, 0); function calculateTrade( MarketParameters memory market, CashGroupParameters memory cashGroup, int256 fCashToAccount, uint256 timeToMaturity, uint256 marketIndex ) internal view returns (int256, int256) { if (market.totalfCash <= fCashToAccount) return (0, 0); (int256 rateScalar, int256 totalCashUnderlying, int256 rateAnchor) = getExchangeRateFactors(market, cashGroup, timeToMaturity, marketIndex); int256 preFeeExchangeRate; { bool success; (preFeeExchangeRate, success) = _getExchangeRate( market.totalfCash, totalCashUnderlying, rateScalar, rateAnchor, fCashToAccount ); if (!success) return (0, 0); } _getNetCashAmountsUnderlying( cashGroup, preFeeExchangeRate, fCashToAccount, timeToMaturity ); { market.totalfCash = market.totalfCash.subNoNeg(fCashToAccount); market.lastImpliedRate = getImpliedRate( market.totalfCash, totalCashUnderlying.add(netCashToMarket), rateScalar, rateAnchor, timeToMaturity ); if (market.lastImpliedRate == 0) return (0, 0); } return _setNewMarketState( market, cashGroup.assetRate, netCashToAccount, netCashToMarket, netCashToReserve ); } function getExchangeRateFactors( MarketParameters memory market, CashGroupParameters memory cashGroup, uint256 timeToMaturity, uint256 marketIndex ) internal pure returns ( int256, int256, int256 ) { int256 rateScalar = cashGroup.getRateScalar(marketIndex, timeToMaturity); int256 totalCashUnderlying = cashGroup.assetRate.convertToUnderlying(market.totalAssetCash); if (market.totalfCash == 0 || totalCashUnderlying == 0) return (0, 0, 0); int256 rateAnchor; { bool success; (rateAnchor, success) = _getRateAnchor( market.totalfCash, market.lastImpliedRate, totalCashUnderlying, rateScalar, timeToMaturity ); if (!success) return (0, 0, 0); } return (rateScalar, totalCashUnderlying, rateAnchor); } function getExchangeRateFactors( MarketParameters memory market, CashGroupParameters memory cashGroup, uint256 timeToMaturity, uint256 marketIndex ) internal pure returns ( int256, int256, int256 ) { int256 rateScalar = cashGroup.getRateScalar(marketIndex, timeToMaturity); int256 totalCashUnderlying = cashGroup.assetRate.convertToUnderlying(market.totalAssetCash); if (market.totalfCash == 0 || totalCashUnderlying == 0) return (0, 0, 0); int256 rateAnchor; { bool success; (rateAnchor, success) = _getRateAnchor( market.totalfCash, market.lastImpliedRate, totalCashUnderlying, rateScalar, timeToMaturity ); if (!success) return (0, 0, 0); } return (rateScalar, totalCashUnderlying, rateAnchor); } function _getNetCashAmountsUnderlying( CashGroupParameters memory cashGroup, int256 preFeeExchangeRate, int256 fCashToAccount, uint256 timeToMaturity ) private pure returns ( int256, int256, int256 ) { int256 preFeeCashToAccount = fCashToAccount.divInRatePrecision(preFeeExchangeRate).neg(); int256 fee = getExchangeRateFromImpliedRate(cashGroup.getTotalFee(), timeToMaturity); if (fCashToAccount > 0) { int256 postFeeExchangeRate = preFeeExchangeRate.divInRatePrecision(fee); if (postFeeExchangeRate < Constants.RATE_PRECISION) return (0, 0, 0); fee = preFeeCashToAccount.mulInRatePrecision(Constants.RATE_PRECISION.sub(fee)); fee = preFeeCashToAccount.mul(Constants.RATE_PRECISION.sub(fee)).div(fee).neg(); } int256 cashToReserve = fee.mul(cashGroup.getReserveFeeShare()).div(Constants.PERCENTAGE_DECIMALS); return ( cashToReserve ); } function _getNetCashAmountsUnderlying( CashGroupParameters memory cashGroup, int256 preFeeExchangeRate, int256 fCashToAccount, uint256 timeToMaturity ) private pure returns ( int256, int256, int256 ) { int256 preFeeCashToAccount = fCashToAccount.divInRatePrecision(preFeeExchangeRate).neg(); int256 fee = getExchangeRateFromImpliedRate(cashGroup.getTotalFee(), timeToMaturity); if (fCashToAccount > 0) { int256 postFeeExchangeRate = preFeeExchangeRate.divInRatePrecision(fee); if (postFeeExchangeRate < Constants.RATE_PRECISION) return (0, 0, 0); fee = preFeeCashToAccount.mulInRatePrecision(Constants.RATE_PRECISION.sub(fee)); fee = preFeeCashToAccount.mul(Constants.RATE_PRECISION.sub(fee)).div(fee).neg(); } int256 cashToReserve = fee.mul(cashGroup.getReserveFeeShare()).div(Constants.PERCENTAGE_DECIMALS); return ( cashToReserve ); } } else { preFeeCashToAccount.sub(fee), (preFeeCashToAccount.sub(fee).add(cashToReserve)).neg(), function _setNewMarketState( MarketParameters memory market, AssetRateParameters memory assetRate, int256 netCashToAccount, int256 netCashToMarket, int256 netCashToReserve ) private view returns (int256, int256) { int256 netAssetCashToMarket = assetRate.convertFromUnderlying(netCashToMarket); market.totalAssetCash = market.totalAssetCash.add(netAssetCashToMarket); market.previousTradeTime = block.timestamp; int256 assetCashToReserve = assetRate.convertFromUnderlying(netCashToReserve); int256 netAssetCashToAccount = assetRate.convertFromUnderlying(netCashToAccount); return (netAssetCashToAccount, assetCashToReserve); } function _getRateAnchor( int256 totalfCash, uint256 lastImpliedRate, int256 totalCashUnderlying, int256 rateScalar, uint256 timeToMaturity ) internal pure returns (int256, bool) { int256 newExchangeRate = getExchangeRateFromImpliedRate(lastImpliedRate, timeToMaturity); if (newExchangeRate < Constants.RATE_PRECISION) return (0, false); int256 rateAnchor; { int256 proportion = totalfCash.divInRatePrecision(totalfCash.add(totalCashUnderlying)); (int256 lnProportion, bool success) = _logProportion(proportion); if (!success) return (0, false); rateAnchor = newExchangeRate.sub(lnProportion.divInRatePrecision(rateScalar)); } return (rateAnchor, true); } function _getRateAnchor( int256 totalfCash, uint256 lastImpliedRate, int256 totalCashUnderlying, int256 rateScalar, uint256 timeToMaturity ) internal pure returns (int256, bool) { int256 newExchangeRate = getExchangeRateFromImpliedRate(lastImpliedRate, timeToMaturity); if (newExchangeRate < Constants.RATE_PRECISION) return (0, false); int256 rateAnchor; { int256 proportion = totalfCash.divInRatePrecision(totalfCash.add(totalCashUnderlying)); (int256 lnProportion, bool success) = _logProportion(proportion); if (!success) return (0, false); rateAnchor = newExchangeRate.sub(lnProportion.divInRatePrecision(rateScalar)); } return (rateAnchor, true); } function getImpliedRate( int256 totalfCash, int256 totalCashUnderlying, int256 rateScalar, int256 rateAnchor, uint256 timeToMaturity ) internal pure returns (uint256) { (int256 exchangeRate, bool success) = _getExchangeRate(totalfCash, totalCashUnderlying, rateScalar, rateAnchor, 0); if (!success) return 0; int128 rate = ABDKMath64x64.fromInt(exchangeRate); int128 rateScaled = ABDKMath64x64.div(rate, Constants.RATE_PRECISION_64x64); int128 lnRateScaled = ABDKMath64x64.ln(rateScaled); uint256 lnRate = ABDKMath64x64.toUInt(ABDKMath64x64.mul(lnRateScaled, Constants.RATE_PRECISION_64x64)); uint256 impliedRate = lnRate.mul(Constants.IMPLIED_RATE_TIME).div(timeToMaturity); if (impliedRate > type(uint32).max) return 0; return impliedRate; } function getExchangeRateFromImpliedRate(uint256 impliedRate, uint256 timeToMaturity) internal pure returns (int256) { int128 expValue = ABDKMath64x64.fromUInt( impliedRate.mul(timeToMaturity).div(Constants.IMPLIED_RATE_TIME) ); int128 expValueScaled = ABDKMath64x64.div(expValue, Constants.RATE_PRECISION_64x64); int128 expResult = ABDKMath64x64.exp(expValueScaled); int128 expResultScaled = ABDKMath64x64.mul(expResult, Constants.RATE_PRECISION_64x64); return ABDKMath64x64.toInt(expResultScaled); } function _getExchangeRate( int256 totalfCash, int256 totalCashUnderlying, int256 rateScalar, int256 rateAnchor, int256 fCashToAccount ) internal pure returns (int256, bool) { int256 numerator = totalfCash.subNoNeg(fCashToAccount); int256 proportion = numerator.divInRatePrecision(totalfCash.add(totalCashUnderlying)); if (proportion > Constants.MAX_MARKET_PROPORTION) return (0, false); (int256 lnProportion, bool success) = _logProportion(proportion); if (!success) return (0, false); int256 rate = lnProportion.divInRatePrecision(rateScalar).add(rateAnchor); if (rate < Constants.RATE_PRECISION) { return (0, false); return (rate, true); } } function _getExchangeRate( int256 totalfCash, int256 totalCashUnderlying, int256 rateScalar, int256 rateAnchor, int256 fCashToAccount ) internal pure returns (int256, bool) { int256 numerator = totalfCash.subNoNeg(fCashToAccount); int256 proportion = numerator.divInRatePrecision(totalfCash.add(totalCashUnderlying)); if (proportion > Constants.MAX_MARKET_PROPORTION) return (0, false); (int256 lnProportion, bool success) = _logProportion(proportion); if (!success) return (0, false); int256 rate = lnProportion.divInRatePrecision(rateScalar).add(rateAnchor); if (rate < Constants.RATE_PRECISION) { return (0, false); return (rate, true); } } } else { function _logProportion(int256 proportion) internal pure returns (int256, bool) { if (proportion == Constants.RATE_PRECISION) return (0, false); int256 logitP = proportion.divInRatePrecision(Constants.RATE_PRECISION.sub(proportion)); int128 abdkProportion = ABDKMath64x64.fromInt(logitP); if (abdkProportion <= 0) return (0, false); int256 result = ABDKMath64x64.toInt( ABDKMath64x64.mul( ABDKMath64x64.sub( ABDKMath64x64.ln(abdkProportion), Constants.LOG_RATE_PRECISION_64x64 ), Constants.RATE_PRECISION_64x64 ) ); return (result, true); } function _updateRateOracle( uint256 previousTradeTime, uint256 lastImpliedRate, uint256 oracleRate, uint256 rateOracleTimeWindow, uint256 blockTime ) private pure returns (uint256) { if (previousTradeTime > blockTime) return lastImpliedRate; uint256 timeDiff = blockTime.sub(previousTradeTime); if (timeDiff > rateOracleTimeWindow) { return lastImpliedRate; } timeDiff.mul(uint256(Constants.RATE_PRECISION)).div(rateOracleTimeWindow); uint256 newOracleRate = (lastImpliedRate.mul(lastTradeWeight).add(oracleRate.mul(oracleWeight))).div( uint256(Constants.RATE_PRECISION) ); return newOracleRate; } function _updateRateOracle( uint256 previousTradeTime, uint256 lastImpliedRate, uint256 oracleRate, uint256 rateOracleTimeWindow, uint256 blockTime ) private pure returns (uint256) { if (previousTradeTime > blockTime) return lastImpliedRate; uint256 timeDiff = blockTime.sub(previousTradeTime); if (timeDiff > rateOracleTimeWindow) { return lastImpliedRate; } timeDiff.mul(uint256(Constants.RATE_PRECISION)).div(rateOracleTimeWindow); uint256 newOracleRate = (lastImpliedRate.mul(lastTradeWeight).add(oracleRate.mul(oracleWeight))).div( uint256(Constants.RATE_PRECISION) ); return newOracleRate; } uint256 lastTradeWeight = uint256 oracleWeight = uint256(Constants.RATE_PRECISION).sub(lastTradeWeight); function getOracleRate( uint256 currencyId, uint256 maturity, uint256 rateOracleTimeWindow, uint256 blockTime ) internal view returns (uint256) { mapping(uint256 => mapping(uint256 => mapping(uint256 => MarketStorage))) storage store = LibStorage.getMarketStorage(); uint256 settlementDate = DateTime.getReferenceTime(blockTime) + Constants.QUARTER; MarketStorage storage marketStorage = store[currencyId][maturity][settlementDate]; uint256 lastImpliedRate = marketStorage.lastImpliedRate; uint256 oracleRate = marketStorage.oracleRate; uint256 previousTradeTime = marketStorage.previousTradeTime; require(oracleRate > 0, "Market not initialized"); return _updateRateOracle( previousTradeTime, lastImpliedRate, oracleRate, rateOracleTimeWindow, blockTime ); } function _loadMarketStorage( MarketParameters memory market, uint256 currencyId, uint256 maturity, bool needsLiquidity, uint256 settlementDate ) private view { mapping(uint256 => mapping(uint256 => mapping(uint256 => MarketStorage))) storage store = LibStorage.getMarketStorage(); MarketStorage storage marketStorage = store[currencyId][maturity][settlementDate]; bytes32 slot; assembly { slot := marketStorage.slot } market.storageSlot = slot; market.maturity = maturity; market.totalfCash = marketStorage.totalfCash; market.totalAssetCash = marketStorage.totalAssetCash; market.lastImpliedRate = marketStorage.lastImpliedRate; market.oracleRate = marketStorage.oracleRate; market.previousTradeTime = marketStorage.previousTradeTime; if (needsLiquidity) { market.totalLiquidity = marketStorage.totalLiquidity; market.totalLiquidity = 0; } } function _loadMarketStorage( MarketParameters memory market, uint256 currencyId, uint256 maturity, bool needsLiquidity, uint256 settlementDate ) private view { mapping(uint256 => mapping(uint256 => mapping(uint256 => MarketStorage))) storage store = LibStorage.getMarketStorage(); MarketStorage storage marketStorage = store[currencyId][maturity][settlementDate]; bytes32 slot; assembly { slot := marketStorage.slot } market.storageSlot = slot; market.maturity = maturity; market.totalfCash = marketStorage.totalfCash; market.totalAssetCash = marketStorage.totalAssetCash; market.lastImpliedRate = marketStorage.lastImpliedRate; market.oracleRate = marketStorage.oracleRate; market.previousTradeTime = marketStorage.previousTradeTime; if (needsLiquidity) { market.totalLiquidity = marketStorage.totalLiquidity; market.totalLiquidity = 0; } } function _loadMarketStorage( MarketParameters memory market, uint256 currencyId, uint256 maturity, bool needsLiquidity, uint256 settlementDate ) private view { mapping(uint256 => mapping(uint256 => mapping(uint256 => MarketStorage))) storage store = LibStorage.getMarketStorage(); MarketStorage storage marketStorage = store[currencyId][maturity][settlementDate]; bytes32 slot; assembly { slot := marketStorage.slot } market.storageSlot = slot; market.maturity = maturity; market.totalfCash = marketStorage.totalfCash; market.totalAssetCash = marketStorage.totalAssetCash; market.lastImpliedRate = marketStorage.lastImpliedRate; market.oracleRate = marketStorage.oracleRate; market.previousTradeTime = marketStorage.previousTradeTime; if (needsLiquidity) { market.totalLiquidity = marketStorage.totalLiquidity; market.totalLiquidity = 0; } } } else { function _getMarketStoragePointer( MarketParameters memory market ) private pure returns (MarketStorage storage marketStorage) { bytes32 slot = market.storageSlot; assembly { marketStorage.slot := slot } } function _getMarketStoragePointer( MarketParameters memory market ) private pure returns (MarketStorage storage marketStorage) { bytes32 slot = market.storageSlot; assembly { marketStorage.slot := slot } } function _setMarketStorageForLiquidity(MarketParameters memory market) internal { MarketStorage storage marketStorage = _getMarketStoragePointer(market); uint32 storedOracleRate = marketStorage.oracleRate; _setMarketStorage( marketStorage, market.totalfCash, market.totalAssetCash, market.lastImpliedRate, storedOracleRate, market.previousTradeTime ); _setTotalLiquidity(marketStorage, market.totalLiquidity); } function setMarketStorageForInitialize( MarketParameters memory market, uint256 currencyId, uint256 settlementDate ) internal { mapping(uint256 => mapping(uint256 => mapping(uint256 => MarketStorage))) storage store = LibStorage.getMarketStorage(); MarketStorage storage marketStorage = store[currencyId][market.maturity][settlementDate]; _setMarketStorage( marketStorage, market.totalfCash, market.totalAssetCash, market.lastImpliedRate, market.oracleRate, market.previousTradeTime ); _setTotalLiquidity(marketStorage, market.totalLiquidity); } function _setTotalLiquidity( MarketStorage storage marketStorage, int256 totalLiquidity ) internal { marketStorage.totalLiquidity = uint80(totalLiquidity); } function _setMarketStorage( MarketStorage storage marketStorage, int256 totalfCash, int256 totalAssetCash, uint256 lastImpliedRate, uint256 oracleRate, uint256 previousTradeTime ) private { marketStorage.totalfCash = uint80(totalfCash); marketStorage.totalAssetCash = uint80(totalAssetCash); marketStorage.lastImpliedRate = uint32(lastImpliedRate); marketStorage.oracleRate = uint32(oracleRate); marketStorage.previousTradeTime = uint32(previousTradeTime); } function loadMarket( MarketParameters memory market, uint256 currencyId, uint256 maturity, uint256 blockTime, bool needsLiquidity, uint256 rateOracleTimeWindow ) internal view { uint256 settlementDate = DateTime.getReferenceTime(blockTime) + Constants.QUARTER; loadMarketWithSettlementDate( market, currencyId, maturity, blockTime, needsLiquidity, rateOracleTimeWindow, settlementDate ); } function loadMarketWithSettlementDate( MarketParameters memory market, uint256 currencyId, uint256 maturity, uint256 blockTime, bool needsLiquidity, uint256 rateOracleTimeWindow, uint256 settlementDate ) internal view { _loadMarketStorage(market, currencyId, maturity, needsLiquidity, settlementDate); market.oracleRate = _updateRateOracle( market.previousTradeTime, market.lastImpliedRate, market.oracleRate, rateOracleTimeWindow, blockTime ); } function loadSettlementMarket( MarketParameters memory market, uint256 currencyId, uint256 maturity, uint256 settlementDate ) internal view { _loadMarketStorage(market, currencyId, maturity, true, settlementDate); } function getfCashGivenCashAmount( int256 totalfCash, int256 netCashToAccount, int256 totalCashUnderlying, int256 rateScalar, int256 rateAnchor, int256 feeRate, int256 maxDelta ) internal pure returns (int256) { require(maxDelta >= 0); int256 fCashChangeToAccountGuess = netCashToAccount.mulInRatePrecision(rateAnchor).neg(); for (uint8 i = 0; i < 250; i++) { (int256 exchangeRate, bool success) = _getExchangeRate( totalfCash, totalCashUnderlying, rateScalar, rateAnchor, fCashChangeToAccountGuess ); int256 delta = _calculateDelta( netCashToAccount, totalfCash, totalCashUnderlying, rateScalar, fCashChangeToAccountGuess, exchangeRate, feeRate ); if (delta.abs() <= maxDelta) return fCashChangeToAccountGuess; fCashChangeToAccountGuess = fCashChangeToAccountGuess.sub(delta); } revert("No convergence"); } function getfCashGivenCashAmount( int256 totalfCash, int256 netCashToAccount, int256 totalCashUnderlying, int256 rateScalar, int256 rateAnchor, int256 feeRate, int256 maxDelta ) internal pure returns (int256) { require(maxDelta >= 0); int256 fCashChangeToAccountGuess = netCashToAccount.mulInRatePrecision(rateAnchor).neg(); for (uint8 i = 0; i < 250; i++) { (int256 exchangeRate, bool success) = _getExchangeRate( totalfCash, totalCashUnderlying, rateScalar, rateAnchor, fCashChangeToAccountGuess ); int256 delta = _calculateDelta( netCashToAccount, totalfCash, totalCashUnderlying, rateScalar, fCashChangeToAccountGuess, exchangeRate, feeRate ); if (delta.abs() <= maxDelta) return fCashChangeToAccountGuess; fCashChangeToAccountGuess = fCashChangeToAccountGuess.sub(delta); } revert("No convergence"); } function _calculateDelta( int256 cashAmount, int256 totalfCash, int256 totalCashUnderlying, int256 rateScalar, int256 fCashGuess, int256 exchangeRate, int256 feeRate ) private pure returns (int256) { int256 derivative; int256 denominator = rateScalar.mulInRatePrecision( (totalfCash.sub(fCashGuess)).mul(totalCashUnderlying.add(fCashGuess)) ); if (fCashGuess > 0) { exchangeRate = exchangeRate.divInRatePrecision(feeRate); derivative = cashAmount .mul(totalfCash.add(totalCashUnderlying)) .divInRatePrecision(feeRate); exchangeRate = exchangeRate.mulInRatePrecision(feeRate); derivative = cashAmount.mulInRatePrecision( feeRate.mul(totalfCash.add(totalCashUnderlying)) ); } numerator = numerator.add(fCashGuess); } function _calculateDelta( int256 cashAmount, int256 totalfCash, int256 totalCashUnderlying, int256 rateScalar, int256 fCashGuess, int256 exchangeRate, int256 feeRate ) private pure returns (int256) { int256 derivative; int256 denominator = rateScalar.mulInRatePrecision( (totalfCash.sub(fCashGuess)).mul(totalCashUnderlying.add(fCashGuess)) ); if (fCashGuess > 0) { exchangeRate = exchangeRate.divInRatePrecision(feeRate); derivative = cashAmount .mul(totalfCash.add(totalCashUnderlying)) .divInRatePrecision(feeRate); exchangeRate = exchangeRate.mulInRatePrecision(feeRate); derivative = cashAmount.mulInRatePrecision( feeRate.mul(totalfCash.add(totalCashUnderlying)) ); } numerator = numerator.add(fCashGuess); } } else { derivative = Constants.INTERNAL_TOKEN_PRECISION.sub(derivative.div(denominator)); int256 numerator = cashAmount.mulInRatePrecision(exchangeRate); return numerator.mul(Constants.INTERNAL_TOKEN_PRECISION).div(derivative); }
14,585,093
[ 1, 2747, 6895, 460, 364, 279, 10336, 3398, 1105, 92, 1105, 3571, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 12083, 6622, 278, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 565, 1450, 14060, 1702, 5034, 364, 509, 5034, 31, 203, 565, 1450, 385, 961, 1114, 364, 385, 961, 1114, 2402, 31, 203, 565, 1450, 10494, 4727, 364, 10494, 4727, 2402, 31, 203, 203, 565, 509, 5034, 3238, 5381, 4552, 1105, 273, 374, 92, 27, 8998, 8998, 18343, 42, 31, 203, 203, 565, 445, 527, 48, 18988, 24237, 12, 3882, 278, 2402, 3778, 13667, 16, 509, 5034, 3310, 39, 961, 13, 203, 3639, 2713, 203, 3639, 1135, 261, 474, 5034, 4501, 372, 24237, 5157, 16, 509, 5034, 284, 39, 961, 13, 203, 97, 203, 683, 9454, 18035, 560, 3602, 20, 18, 27, 18, 20, 31, 203, 565, 288, 203, 3639, 2583, 12, 27151, 18, 4963, 48, 18988, 24237, 405, 374, 16, 315, 49, 30, 3634, 4501, 372, 24237, 8863, 203, 3639, 309, 261, 9406, 39, 961, 422, 374, 13, 327, 261, 20, 16, 374, 1769, 203, 203, 3639, 4501, 372, 24237, 5157, 273, 13667, 18, 4963, 48, 18988, 24237, 18, 16411, 12, 9406, 39, 961, 2934, 2892, 12, 27151, 18, 4963, 6672, 39, 961, 1769, 203, 3639, 284, 39, 961, 273, 13667, 18, 4963, 74, 39, 961, 18, 16411, 12, 9406, 39, 961, 2934, 2892, 12, 27151, 18, 4963, 6672, 39, 961, 1769, 203, 203, 3639, 13667, 18, 4963, 48, 18988, 24237, 273, 13667, 18, 4963, 48, 18988, 24237, 18, 1289, 12, 549, 372, 24237, 5157, 1769, 203, 3639, 13667, 18, 4963, 74, 39, 961, 273, 13667, 18, 4963, 74, 39, 2 ]
/** *Submitted for verification at FtmScan.com on 2021-10-26 */ // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; /** * @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); } } } } struct StrategyParams { uint256 performanceFee; uint256 activation; uint256 debtRatio; uint256 minDebtPerHarvest; uint256 maxDebtPerHarvest; uint256 lastReport; uint256 totalDebt; uint256 totalGain; uint256 totalLoss; } /** * @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 ); } interface VaultAPI is IERC20 { function name() external view returns (string calldata); function symbol() external view returns (string calldata); function decimals() external view returns (uint256); function apiVersion() external pure returns (string memory); function permit( address owner, address spender, uint256 amount, uint256 expiry, bytes calldata signature ) external returns (bool); // NOTE: Vyper produces multiple signatures for a given function with "default" args function deposit() external returns (uint256); function deposit(uint256 amount) external returns (uint256); function deposit(uint256 amount, address recipient) external returns (uint256); // NOTE: Vyper produces multiple signatures for a given function with "default" args function withdraw() external returns (uint256); function withdraw(uint256 maxShares) external returns (uint256); function withdraw(uint256 maxShares, address recipient) external returns (uint256); function token() external view returns (address); function strategies(address _strategy) external view returns (StrategyParams memory); function pricePerShare() external view returns (uint256); function totalAssets() external view returns (uint256); function depositLimit() external view returns (uint256); function maxAvailableShares() external view returns (uint256); /** * View how much the Vault would increase this Strategy's borrow limit, * based on its present performance (since its last report). Can be used to * determine expectedReturn in your Strategy. */ function creditAvailable() external view returns (uint256); /** * View how much the Vault would like to pull back from the Strategy, * based on its present performance (since its last report). Can be used to * determine expectedReturn in your Strategy. */ function debtOutstanding() external view returns (uint256); /** * View how much the Vault expect this Strategy to return at the current * block, based on its present performance (since its last report). Can be * used to determine expectedReturn in your Strategy. */ function expectedReturn() external view returns (uint256); /** * This is the main contact point where the Strategy interacts with the * Vault. It is critical that this call is handled as intended by the * Strategy. Therefore, this function will be called by BaseStrategy to * make sure the integration is correct. */ function report( uint256 _gain, uint256 _loss, uint256 _debtPayment ) external returns (uint256); /** * This function should only be used in the scenario where the Strategy is * being retired but no migration of the positions are possible, or in the * extreme scenario that the Strategy needs to be put into "Emergency Exit" * mode in order for it to exit as quickly as possible. The latter scenario * could be for any reason that is considered "critical" that the Strategy * exits its position as fast as possible, such as a sudden change in * market conditions leading to losses, or an imminent failure in an * external dependency. */ function revokeStrategy() external; /** * View the governance address of the Vault to assert privileged functions * can only be called by governance. The Strategy serves the Vault, so it * is subject to governance defined by the Vault. */ function governance() external view returns (address); /** * View the management address of the Vault to assert privileged functions * can only be called by management. The Strategy serves the Vault, so it * is subject to management defined by the Vault. */ function management() external view returns (address); /** * View the guardian address of the Vault to assert privileged functions * can only be called by guardian. The Strategy serves the Vault, so it * is subject to guardian defined by the Vault. */ function guardian() external view returns (address); } /** * This interface is here for the keeper bot to use. */ interface StrategyAPI { function name() external view returns (string memory); function vault() external view returns (address); function want() external view returns (address); function apiVersion() external pure returns (string memory); function keeper() external view returns (address); function isActive() external view returns (bool); function delegatedAssets() external view returns (uint256); function estimatedTotalAssets() external view returns (uint256); function tendTrigger(uint256 callCost) external view returns (bool); function tend() external; function harvestTrigger(uint256 callCost) external view returns (bool); function harvest() external; event Harvested( uint256 profit, uint256 loss, uint256 debtPayment, uint256 debtOutstanding ); } interface HealthCheck { function check( uint256 profit, uint256 loss, uint256 debtPayment, uint256 debtOutstanding, uint256 totalDebt ) external view returns (bool); } /** * @title Yearn Base Strategy * @author yearn.finance * @notice * BaseStrategy implements all of the required functionality to interoperate * closely with the Vault contract. This contract should be inherited and the * abstract methods implemented to adapt the Strategy to the particular needs * it has to create a return. * * Of special interest is the relationship between `harvest()` and * `vault.report()'. `harvest()` may be called simply because enough time has * elapsed since the last report, and not because any funds need to be moved * or positions adjusted. This is critical so that the Vault may maintain an * accurate picture of the Strategy's performance. See `vault.report()`, * `harvest()`, and `harvestTrigger()` for further details. */ abstract contract BaseStrategy { using SafeMath for uint256; using SafeERC20 for IERC20; string public metadataURI; // health checks bool public doHealthCheck; address public healthCheck; /** * @notice * Used to track which version of `StrategyAPI` this Strategy * implements. * @dev The Strategy's version must match the Vault's `API_VERSION`. * @return A string which holds the current API version of this contract. */ function apiVersion() public pure returns (string memory) { return "0.4.3"; } /** * @notice This Strategy's name. * @dev * You can use this field to manage the "version" of this Strategy, e.g. * `StrategySomethingOrOtherV1`. However, "API Version" is managed by * `apiVersion()` function above. * @return This Strategy's name. */ function name() external view virtual returns (string memory); /** * @notice * The amount (priced in want) of the total assets managed by this strategy should not count * towards Yearn's TVL calculations. * @dev * You can override this field to set it to a non-zero value if some of the assets of this * Strategy is somehow delegated inside another part of of Yearn's ecosystem e.g. another Vault. * Note that this value must be strictly less than or equal to the amount provided by * `estimatedTotalAssets()` below, as the TVL calc will be total assets minus delegated assets. * Also note that this value is used to determine the total assets under management by this * strategy, for the purposes of computing the management fee in `Vault` * @return * The amount of assets this strategy manages that should not be included in Yearn's Total Value * Locked (TVL) calculation across it's ecosystem. */ function delegatedAssets() external view virtual returns (uint256) { return 0; } VaultAPI public vault; address public strategist; address public rewards; address public keeper; IERC20 public want; // So indexers can keep track of this event Harvested( uint256 profit, uint256 loss, uint256 debtPayment, uint256 debtOutstanding ); event UpdatedStrategist(address newStrategist); event UpdatedKeeper(address newKeeper); event UpdatedRewards(address rewards); event UpdatedMinReportDelay(uint256 delay); event UpdatedMaxReportDelay(uint256 delay); event UpdatedProfitFactor(uint256 profitFactor); event UpdatedDebtThreshold(uint256 debtThreshold); event EmergencyExitEnabled(); event UpdatedMetadataURI(string metadataURI); // The minimum number of seconds between harvest calls. See // `setMinReportDelay()` for more details. uint256 public minReportDelay; // The maximum number of seconds between harvest calls. See // `setMaxReportDelay()` for more details. uint256 public maxReportDelay; // The minimum multiple that `callCost` must be above the credit/profit to // be "justifiable". See `setProfitFactor()` for more details. uint256 public profitFactor; // Use this to adjust the threshold at which running a debt causes a // harvest trigger. See `setDebtThreshold()` for more details. uint256 public debtThreshold; // See note on `setEmergencyExit()`. bool public emergencyExit; // modifiers modifier onlyAuthorized() { require( msg.sender == strategist || msg.sender == governance(), "!authorized" ); _; } modifier onlyEmergencyAuthorized() { require( msg.sender == strategist || msg.sender == governance() || msg.sender == vault.guardian() || msg.sender == vault.management(), "!authorized" ); _; } modifier onlyStrategist() { require(msg.sender == strategist, "!strategist"); _; } modifier onlyGovernance() { require(msg.sender == governance(), "!authorized"); _; } modifier onlyKeepers() { require( msg.sender == keeper || msg.sender == strategist || msg.sender == governance() || msg.sender == vault.guardian() || msg.sender == vault.management(), "!authorized" ); _; } modifier onlyVaultManagers() { require( msg.sender == vault.management() || msg.sender == governance(), "!authorized" ); _; } constructor(address _vault) public { _initialize(_vault, msg.sender, msg.sender, msg.sender); } /** * @notice * Initializes the Strategy, this is called only once, when the * contract is deployed. * @dev `_vault` should implement `VaultAPI`. * @param _vault The address of the Vault responsible for this Strategy. * @param _strategist The address to assign as `strategist`. * The strategist is able to change the reward address * @param _rewards The address to use for pulling rewards. * @param _keeper The adddress of the _keeper. _keeper * can harvest and tend a strategy. */ function _initialize( address _vault, address _strategist, address _rewards, address _keeper ) internal { require(address(want) == address(0), "Strategy already initialized"); vault = VaultAPI(_vault); want = IERC20(vault.token()); want.safeApprove(_vault, uint256(-1)); // Give Vault unlimited access (might save gas) strategist = _strategist; rewards = _rewards; keeper = _keeper; // initialize variables minReportDelay = 0; maxReportDelay = 86400; profitFactor = 100; debtThreshold = 0; vault.approve(rewards, uint256(-1)); // Allow rewards to be pulled } function setHealthCheck(address _healthCheck) external onlyVaultManagers { healthCheck = _healthCheck; } function setDoHealthCheck(bool _doHealthCheck) external onlyVaultManagers { doHealthCheck = _doHealthCheck; } /** * @notice * Used to change `strategist`. * * This may only be called by governance or the existing strategist. * @param _strategist The new address to assign as `strategist`. */ function setStrategist(address _strategist) external onlyAuthorized { require(_strategist != address(0)); strategist = _strategist; emit UpdatedStrategist(_strategist); } /** * @notice * Used to change `keeper`. * * `keeper` is the only address that may call `tend()` or `harvest()`, * other than `governance()` or `strategist`. However, unlike * `governance()` or `strategist`, `keeper` may *only* call `tend()` * and `harvest()`, and no other authorized functions, following the * principle of least privilege. * * This may only be called by governance or the strategist. * @param _keeper The new address to assign as `keeper`. */ function setKeeper(address _keeper) external onlyAuthorized { require(_keeper != address(0)); keeper = _keeper; emit UpdatedKeeper(_keeper); } /** * @notice * Used to change `rewards`. EOA or smart contract which has the permission * to pull rewards from the vault. * * This may only be called by the strategist. * @param _rewards The address to use for pulling rewards. */ function setRewards(address _rewards) external onlyStrategist { require(_rewards != address(0)); vault.approve(rewards, 0); rewards = _rewards; vault.approve(rewards, uint256(-1)); emit UpdatedRewards(_rewards); } /** * @notice * Used to change `minReportDelay`. `minReportDelay` is the minimum number * of blocks that should pass for `harvest()` to be called. * * For external keepers (such as the Keep3r network), this is the minimum * time between jobs to wait. (see `harvestTrigger()` * for more details.) * * This may only be called by governance or the strategist. * @param _delay The minimum number of seconds to wait between harvests. */ function setMinReportDelay(uint256 _delay) external onlyAuthorized { minReportDelay = _delay; emit UpdatedMinReportDelay(_delay); } /** * @notice * Used to change `maxReportDelay`. `maxReportDelay` is the maximum number * of blocks that should pass for `harvest()` to be called. * * For external keepers (such as the Keep3r network), this is the maximum * time between jobs to wait. (see `harvestTrigger()` * for more details.) * * This may only be called by governance or the strategist. * @param _delay The maximum number of seconds to wait between harvests. */ function setMaxReportDelay(uint256 _delay) external onlyAuthorized { maxReportDelay = _delay; emit UpdatedMaxReportDelay(_delay); } /** * @notice * Used to change `profitFactor`. `profitFactor` is used to determine * if it's worthwhile to harvest, given gas costs. (See `harvestTrigger()` * for more details.) * * This may only be called by governance or the strategist. * @param _profitFactor A ratio to multiply anticipated * `harvest()` gas cost against. */ function setProfitFactor(uint256 _profitFactor) external onlyAuthorized { profitFactor = _profitFactor; emit UpdatedProfitFactor(_profitFactor); } /** * @notice * Sets how far the Strategy can go into loss without a harvest and report * being required. * * By default this is 0, meaning any losses would cause a harvest which * will subsequently report the loss to the Vault for tracking. (See * `harvestTrigger()` for more details.) * * This may only be called by governance or the strategist. * @param _debtThreshold How big of a loss this Strategy may carry without * being required to report to the Vault. */ function setDebtThreshold(uint256 _debtThreshold) external onlyAuthorized { debtThreshold = _debtThreshold; emit UpdatedDebtThreshold(_debtThreshold); } /** * @notice * Used to change `metadataURI`. `metadataURI` is used to store the URI * of the file describing the strategy. * * This may only be called by governance or the strategist. * @param _metadataURI The URI that describe the strategy. */ function setMetadataURI(string calldata _metadataURI) external onlyAuthorized { metadataURI = _metadataURI; emit UpdatedMetadataURI(_metadataURI); } /** * Resolve governance address from Vault contract, used to make assertions * on protected functions in the Strategy. */ function governance() internal view returns (address) { return vault.governance(); } /** * @notice * Provide an accurate conversion from `_amtInWei` (denominated in wei) * to `want` (using the native decimal characteristics of `want`). * @dev * Care must be taken when working with decimals to assure that the conversion * is compatible. As an example: * * given 1e17 wei (0.1 ETH) as input, and want is USDC (6 decimals), * with USDC/ETH = 1800, this should give back 1800000000 (180 USDC) * * @param _amtInWei The amount (in wei/1e-18 ETH) to convert to `want` * @return The amount in `want` of `_amtInEth` converted to `want` **/ function ethToWant(uint256 _amtInWei) public view virtual returns (uint256); /** * @notice * Provide an accurate estimate for the total amount of assets * (principle + return) that this Strategy is currently managing, * denominated in terms of `want` tokens. * * This total should be "realizable" e.g. the total value that could * *actually* be obtained from this Strategy if it were to divest its * entire position based on current on-chain conditions. * @dev * Care must be taken in using this function, since it relies on external * systems, which could be manipulated by the attacker to give an inflated * (or reduced) value produced by this function, based on current on-chain * conditions (e.g. this function is possible to influence through * flashloan attacks, oracle manipulations, or other DeFi attack * mechanisms). * * It is up to governance to use this function to correctly order this * Strategy relative to its peers in the withdrawal queue to minimize * losses for the Vault based on sudden withdrawals. This value should be * higher than the total debt of the Strategy and higher than its expected * value to be "safe". * @return The estimated total assets in this Strategy. */ function estimatedTotalAssets() public view virtual returns (uint256); /* * @notice * Provide an indication of whether this strategy is currently "active" * in that it is managing an active position, or will manage a position in * the future. This should correlate to `harvest()` activity, so that Harvest * events can be tracked externally by indexing agents. * @return True if the strategy is actively managing a position. */ function isActive() public view returns (bool) { return vault.strategies(address(this)).debtRatio > 0 || estimatedTotalAssets() > 0; } /** * Perform any Strategy unwinding or other calls necessary to capture the * "free return" this Strategy has generated since the last time its core * position(s) were adjusted. Examples include unwrapping extra rewards. * This call is only used during "normal operation" of a Strategy, and * should be optimized to minimize losses as much as possible. * * This method returns any realized profits and/or realized losses * incurred, and should return the total amounts of profits/losses/debt * payments (in `want` tokens) for the Vault's accounting (e.g. * `want.balanceOf(this) >= _debtPayment + _profit`). * * `_debtOutstanding` will be 0 if the Strategy is not past the configured * debt limit, otherwise its value will be how far past the debt limit * the Strategy is. The Strategy's debt limit is configured in the Vault. * * NOTE: `_debtPayment` should be less than or equal to `_debtOutstanding`. * It is okay for it to be less than `_debtOutstanding`, as that * should only used as a guide for how much is left to pay back. * Payments should be made to minimize loss from slippage, debt, * withdrawal fees, etc. * * See `vault.debtOutstanding()`. */ function prepareReturn(uint256 _debtOutstanding) internal virtual returns ( uint256 _profit, uint256 _loss, uint256 _debtPayment ); /** * Perform any adjustments to the core position(s) of this Strategy given * what change the Vault made in the "investable capital" available to the * Strategy. Note that all "free capital" in the Strategy after the report * was made is available for reinvestment. Also note that this number * could be 0, and you should handle that scenario accordingly. * * See comments regarding `_debtOutstanding` on `prepareReturn()`. */ function adjustPosition(uint256 _debtOutstanding) internal virtual; /** * Liquidate up to `_amountNeeded` of `want` of this strategy's positions, * irregardless of slippage. Any excess will be re-invested with `adjustPosition()`. * This function should return the amount of `want` tokens made available by the * liquidation. If there is a difference between them, `_loss` indicates whether the * difference is due to a realized loss, or if there is some other sitution at play * (e.g. locked funds) where the amount made available is less than what is needed. * * NOTE: The invariant `_liquidatedAmount + _loss <= _amountNeeded` should always be maintained */ function liquidatePosition(uint256 _amountNeeded) internal virtual returns (uint256 _liquidatedAmount, uint256 _loss); /** * Liquidate everything and returns the amount that got freed. * This function is used during emergency exit instead of `prepareReturn()` to * liquidate all of the Strategy's positions back to the Vault. */ function liquidateAllPositions() internal virtual returns (uint256 _amountFreed); /** * @notice * Provide a signal to the keeper that `tend()` should be called. The * keeper will provide the estimated gas cost that they would pay to call * `tend()`, and this function should use that estimate to make a * determination if calling it is "worth it" for the keeper. This is not * the only consideration into issuing this trigger, for example if the * position would be negatively affected if `tend()` is not called * shortly, then this can return `true` even if the keeper might be * "at a loss" (keepers are always reimbursed by Yearn). * @dev * `callCostInWei` must be priced in terms of `wei` (1e-18 ETH). * * This call and `harvestTrigger()` should never return `true` at the same * time. * @param callCostInWei The keeper's estimated gas cost to call `tend()` (in wei). * @return `true` if `tend()` should be called, `false` otherwise. */ function tendTrigger(uint256 callCostInWei) public view virtual returns (bool) { // We usually don't need tend, but if there are positions that need // active maintainence, overriding this function is how you would // signal for that. // If your implementation uses the cost of the call in want, you can // use uint256 callCost = ethToWant(callCostInWei); return false; } /** * @notice * Adjust the Strategy's position. The purpose of tending isn't to * realize gains, but to maximize yield by reinvesting any returns. * * See comments on `adjustPosition()`. * * This may only be called by governance, the strategist, or the keeper. */ function tend() external onlyKeepers { // Don't take profits with this call, but adjust for better gains adjustPosition(vault.debtOutstanding()); } /** * @notice * Provide a signal to the keeper that `harvest()` should be called. The * keeper will provide the estimated gas cost that they would pay to call * `harvest()`, and this function should use that estimate to make a * determination if calling it is "worth it" for the keeper. This is not * the only consideration into issuing this trigger, for example if the * position would be negatively affected if `harvest()` is not called * shortly, then this can return `true` even if the keeper might be "at a * loss" (keepers are always reimbursed by Yearn). * @dev * `callCostInWei` must be priced in terms of `wei` (1e-18 ETH). * * This call and `tendTrigger` should never return `true` at the * same time. * * See `min/maxReportDelay`, `profitFactor`, `debtThreshold` to adjust the * strategist-controlled parameters that will influence whether this call * returns `true` or not. These parameters will be used in conjunction * with the parameters reported to the Vault (see `params`) to determine * if calling `harvest()` is merited. * * It is expected that an external system will check `harvestTrigger()`. * This could be a script run off a desktop or cloud bot (e.g. * https://github.com/iearn-finance/yearn-vaults/blob/main/scripts/keep.py), * or via an integration with the Keep3r network (e.g. * https://github.com/Macarse/GenericKeep3rV2/blob/master/contracts/keep3r/GenericKeep3rV2.sol). * @param callCostInWei The keeper's estimated gas cost to call `harvest()` (in wei). * @return `true` if `harvest()` should be called, `false` otherwise. */ function harvestTrigger(uint256 callCostInWei) public view virtual returns (bool) { uint256 callCost = ethToWant(callCostInWei); StrategyParams memory params = vault.strategies(address(this)); // Should not trigger if Strategy is not activated if (params.activation == 0) return false; // Should not trigger if we haven't waited long enough since previous harvest if (block.timestamp.sub(params.lastReport) < minReportDelay) return false; // Should trigger if hasn't been called in a while if (block.timestamp.sub(params.lastReport) >= maxReportDelay) return true; // If some amount is owed, pay it back // NOTE: Since debt is based on deposits, it makes sense to guard against large // changes to the value from triggering a harvest directly through user // behavior. This should ensure reasonable resistance to manipulation // from user-initiated withdrawals as the outstanding debt fluctuates. uint256 outstanding = vault.debtOutstanding(); if (outstanding > debtThreshold) return true; // Check for profits and losses uint256 total = estimatedTotalAssets(); // Trigger if we have a loss to report if (total.add(debtThreshold) < params.totalDebt) return true; uint256 profit = 0; if (total > params.totalDebt) profit = total.sub(params.totalDebt); // We've earned a profit! // Otherwise, only trigger if it "makes sense" economically (gas cost // is <N% of value moved) uint256 credit = vault.creditAvailable(); return (profitFactor.mul(callCost) < credit.add(profit)); } /** * @notice * Harvests the Strategy, recognizing any profits or losses and adjusting * the Strategy's position. * * In the rare case the Strategy is in emergency shutdown, this will exit * the Strategy's position. * * This may only be called by governance, the strategist, or the keeper. * @dev * When `harvest()` is called, the Strategy reports to the Vault (via * `vault.report()`), so in some cases `harvest()` must be called in order * to take in profits, to borrow newly available funds from the Vault, or * otherwise adjust its position. In other cases `harvest()` must be * called to report to the Vault on the Strategy's position, especially if * any losses have occurred. */ function harvest() external onlyKeepers { uint256 profit = 0; uint256 loss = 0; uint256 debtOutstanding = vault.debtOutstanding(); uint256 debtPayment = 0; if (emergencyExit) { // Free up as much capital as possible uint256 amountFreed = liquidateAllPositions(); if (amountFreed < debtOutstanding) { loss = debtOutstanding.sub(amountFreed); } else if (amountFreed > debtOutstanding) { profit = amountFreed.sub(debtOutstanding); } debtPayment = debtOutstanding.sub(loss); } else { // Free up returns for Vault to pull (profit, loss, debtPayment) = prepareReturn(debtOutstanding); } // Allow Vault to take up to the "harvested" balance of this contract, // which is the amount it has earned since the last time it reported to // the Vault. uint256 totalDebt = vault.strategies(address(this)).totalDebt; debtOutstanding = vault.report(profit, loss, debtPayment); // Check if free returns are left, and re-invest them adjustPosition(debtOutstanding); // call healthCheck contract if (doHealthCheck && healthCheck != address(0)) { require( HealthCheck(healthCheck).check( profit, loss, debtPayment, debtOutstanding, totalDebt ), "!healthcheck" ); } else { doHealthCheck = true; } emit Harvested(profit, loss, debtPayment, debtOutstanding); } /** * @notice * Withdraws `_amountNeeded` to `vault`. * * This may only be called by the Vault. * @param _amountNeeded How much `want` to withdraw. * @return _loss Any realized losses */ function withdraw(uint256 _amountNeeded) external returns (uint256 _loss) { require(msg.sender == address(vault), "!vault"); // Liquidate as much as possible to `want`, up to `_amountNeeded` uint256 amountFreed; (amountFreed, _loss) = liquidatePosition(_amountNeeded); // Send it directly back (NOTE: Using `msg.sender` saves some gas here) want.safeTransfer(msg.sender, amountFreed); // NOTE: Reinvest anything leftover on next `tend`/`harvest` } /** * Do anything necessary to prepare this Strategy for migration, such as * transferring any reserve or LP tokens, CDPs, or other tokens or stores of * value. */ function prepareMigration(address _newStrategy) internal virtual; /** * @notice * Transfers all `want` from this Strategy to `_newStrategy`. * * This may only be called by the Vault. * @dev * The new Strategy's Vault must be the same as this Strategy's Vault. * The migration process should be carefully performed to make sure all * the assets are migrated to the new address, which should have never * interacted with the vault before. * @param _newStrategy The Strategy to migrate to. */ function migrate(address _newStrategy) external { require(msg.sender == address(vault)); require(BaseStrategy(_newStrategy).vault() == vault); prepareMigration(_newStrategy); want.safeTransfer(_newStrategy, want.balanceOf(address(this))); } /** * @notice * Activates emergency exit. Once activated, the Strategy will exit its * position upon the next harvest, depositing all funds into the Vault as * quickly as is reasonable given on-chain conditions. * * This may only be called by governance or the strategist. * @dev * See `vault.setEmergencyShutdown()` and `harvest()` for further details. */ function setEmergencyExit() external onlyEmergencyAuthorized { emergencyExit = true; vault.revokeStrategy(); emit EmergencyExitEnabled(); } /** * Override this to add all tokens/tokenized positions this contract * manages on a *persistent* basis (e.g. not just for swapping back to * want ephemerally). * * NOTE: Do *not* include `want`, already included in `sweep` below. * * Example: * ``` * function protectedTokens() internal override view returns (address[] memory) { * address[] memory protected = new address[](3); * protected[0] = tokenA; * protected[1] = tokenB; * protected[2] = tokenC; * return protected; * } * ``` */ function protectedTokens() internal view virtual returns (address[] memory); /** * @notice * Removes tokens from this Strategy that are not the type of tokens * managed by this Strategy. This may be used in case of accidentally * sending the wrong kind of token to this Strategy. * * Tokens will be sent to `governance()`. * * This will fail if an attempt is made to sweep `want`, or any tokens * that are protected by this Strategy. * * This may only be called by governance. * @dev * Implement `protectedTokens()` to specify any additional tokens that * should be protected from sweeping in addition to `want`. * @param _token The token to transfer out of this vault. */ function sweep(address _token) external onlyGovernance { require(_token != address(want), "!want"); require(_token != address(vault), "!shares"); address[] memory _protectedTokens = protectedTokens(); for (uint256 i; i < _protectedTokens.length; i++) require(_token != _protectedTokens[i], "!protected"); IERC20(_token).safeTransfer( governance(), IERC20(_token).balanceOf(address(this)) ); } } abstract contract BaseStrategyInitializable is BaseStrategy { bool public isOriginal = true; event Cloned(address indexed clone); constructor(address _vault) public BaseStrategy(_vault) {} function initialize( address _vault, address _strategist, address _rewards, address _keeper ) external virtual { _initialize(_vault, _strategist, _rewards, _keeper); } function clone(address _vault) external returns (address) { require(isOriginal, "!clone"); return this.clone(_vault, msg.sender, msg.sender, msg.sender); } function clone( address _vault, address _strategist, address _rewards, address _keeper ) external returns (address newStrategy) { // Copied from https://github.com/optionality/clone-factory/blob/master/contracts/CloneFactory.sol bytes20 addressBytes = bytes20(address(this)); assembly { // EIP-1167 bytecode let clone_code := mload(0x40) mstore( clone_code, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000 ) mstore(add(clone_code, 0x14), addressBytes) mstore( add(clone_code, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000 ) newStrategy := create(0, clone_code, 0x37) } BaseStrategyInitializable(newStrategy).initialize( _vault, _strategist, _rewards, _keeper ); emit Cloned(newStrategy); } } interface CTokenI { /*** Market Events ***/ /** * @notice Event emitted when interest is accrued */ event AccrueInterest( uint256 cashPrior, uint256 interestAccumulated, uint256 borrowIndex, uint256 totalBorrows ); /** * @notice Event emitted when tokens are minted */ event Mint(address minter, uint256 mintAmount, uint256 mintTokens); /** * @notice Event emitted when tokens are redeemed */ event Redeem(address redeemer, uint256 redeemAmount, uint256 redeemTokens); /** * @notice Event emitted when underlying is borrowed */ event Borrow( address borrower, uint256 borrowAmount, uint256 accountBorrows, uint256 totalBorrows ); /** * @notice Event emitted when a borrow is repaid */ event RepayBorrow( address payer, address borrower, uint256 repayAmount, uint256 accountBorrows, uint256 totalBorrows ); /** * @notice Event emitted when a borrow is liquidated */ event LiquidateBorrow( address liquidator, address borrower, uint256 repayAmount, address cTokenCollateral, uint256 seizeTokens ); /*** Admin Events ***/ /** * @notice Event emitted when pendingAdmin is changed */ event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin); /** * @notice Event emitted when pendingAdmin is accepted, which means admin is updated */ event NewAdmin(address oldAdmin, address newAdmin); /** * @notice Event emitted when the reserve factor is changed */ event NewReserveFactor( uint256 oldReserveFactorMantissa, uint256 newReserveFactorMantissa ); /** * @notice Event emitted when the reserves are added */ event ReservesAdded( address benefactor, uint256 addAmount, uint256 newTotalReserves ); /** * @notice Event emitted when the reserves are reduced */ event ReservesReduced( address admin, uint256 reduceAmount, uint256 newTotalReserves ); /** * @notice EIP20 Transfer event */ event Transfer(address indexed from, address indexed to, uint256 amount); /** * @notice EIP20 Approval event */ event Approval( address indexed owner, address indexed spender, uint256 amount ); /** * @notice Failure event */ event Failure(uint256 error, uint256 info, uint256 detail); function transfer(address dst, uint256 amount) external returns (bool); function transferFrom( address src, address dst, 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 balanceOf(address owner) external view returns (uint256); function balanceOfUnderlying(address owner) external returns (uint256); function getAccountSnapshot(address account) external view returns ( uint256, uint256, uint256, uint256 ); function borrowRatePerBlock() external view returns (uint256); function supplyRatePerBlock() external view returns (uint256); function totalBorrowsCurrent() external returns (uint256); function borrowBalanceCurrent(address account) external returns (uint256); function borrowBalanceStored(address account) external view returns (uint256); function exchangeRateCurrent() external returns (uint256); function accrualBlockNumber() external view returns (uint256); function exchangeRateStored() external view returns (uint256); function getCash() external view returns (uint256); function accrueInterest() external returns (uint256); function interestRateModel() external view returns (InterestRateModel); function totalReserves() external view returns (uint256); function reserveFactorMantissa() external view returns (uint256); function seize( address liquidator, address borrower, uint256 seizeTokens ) external returns (uint256); function totalBorrows() external view returns (uint256); function totalSupply() external view returns (uint256); } interface CErc20I is CTokenI { function mint(uint256 mintAmount) external returns (uint256); function redeem(uint256 redeemTokens) external returns (uint256); function redeemUnderlying(uint256 redeemAmount) external returns (uint256); function borrow(uint256 borrowAmount) external returns (uint256); function repayBorrow(uint256 repayAmount) external returns (uint256); function repayBorrowBehalf(address borrower, uint256 repayAmount) external returns (uint256); function liquidateBorrow( address borrower, uint256 repayAmount, CTokenI cTokenCollateral ) external returns (uint256); function underlying() external view returns (address); function comptroller() external view returns (address); } interface ComptrollerI { function enterMarkets(address[] calldata cTokens) external returns (uint256[] memory); function exitMarket(address cToken) external returns (uint256); /*** Policy Hooks ***/ function mintAllowed( address cToken, address minter, uint256 mintAmount ) external returns (uint256); function mintVerify( address cToken, address minter, uint256 mintAmount, uint256 mintTokens ) external; function redeemAllowed( address cToken, address redeemer, uint256 redeemTokens ) external returns (uint256); function redeemVerify( address cToken, address redeemer, uint256 redeemAmount, uint256 redeemTokens ) external; function borrowAllowed( address cToken, address borrower, uint256 borrowAmount ) external returns (uint256); function borrowVerify( address cToken, address borrower, uint256 borrowAmount ) external; function repayBorrowAllowed( address cToken, address payer, address borrower, uint256 repayAmount ) external returns (uint256); function repayBorrowVerify( address cToken, address payer, address borrower, uint256 repayAmount, uint256 borrowerIndex ) external; function liquidateBorrowAllowed( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint256 repayAmount ) external returns (uint256); function liquidateBorrowVerify( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint256 repayAmount, uint256 seizeTokens ) external; function seizeAllowed( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint256 seizeTokens ) external returns (uint256); function seizeVerify( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint256 seizeTokens ) external; function transferAllowed( address cToken, address src, address dst, uint256 transferTokens ) external returns (uint256); function transferVerify( address cToken, address src, address dst, uint256 transferTokens ) external; /*** Liquidity/Liquidation Calculations ***/ function liquidateCalculateSeizeTokens( address cTokenBorrowed, address cTokenCollateral, uint256 repayAmount ) external view returns (uint256, uint256); function getAccountLiquidity(address account) external view returns ( uint256, uint256, uint256 ); /*** Comp claims ****/ function claimComp(address holder) external; function claimComp(address holder, CTokenI[] memory cTokens) external; function markets(address ctoken) external view returns ( bool, uint256, bool ); function compSpeeds(address ctoken) external view returns (uint256); // will be deprecated function compSupplySpeeds(address ctoken) external view returns (uint256); function compBorrowSpeeds(address ctoken) external view returns (uint256); function oracle() external view returns (address); } interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint256 amountADesired, uint256 amountBDesired, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns ( uint256 amountA, uint256 amountB, uint256 liquidity ); function addLiquidityETH( address token, uint256 amountTokenDesired, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external payable returns ( uint256 amountToken, uint256 amountETH, uint256 liquidity ); function removeLiquidity( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns (uint256 amountA, uint256 amountB); function removeLiquidityETH( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external returns (uint256 amountToken, uint256 amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountA, uint256 amountB); function removeLiquidityETHWithPermit( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountToken, uint256 amountETH); function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapTokensForExactTokens( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactETHForTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function swapTokensForExactETH( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactTokensForETH( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapETHForExactTokens( uint256 amountOut, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function quote( uint256 amountA, uint256 reserveA, uint256 reserveB ) external pure returns (uint256 amountB); function getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut ) external pure returns (uint256 amountOut); function getAmountIn( uint256 amountOut, uint256 reserveIn, uint256 reserveOut ) external pure returns (uint256 amountIn); function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts); function getAmountsIn(uint256 amountOut, address[] calldata path) external view returns (uint256[] memory amounts); } interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external returns (uint256 amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external; } interface InterestRateModel { /** * @notice Calculates the current borrow interest rate per block * @param cash The total amount of cash the market has * @param borrows The total amount of borrows the market has outstanding * @param reserves The total amount of reserves the market has * @return The borrow rate per block (as a percentage, and scaled by 1e18) */ function getBorrowRate( uint256 cash, uint256 borrows, uint256 reserves ) external view returns (uint256, uint256); /** * @notice Calculates the current supply interest rate per block * @param cash The total amount of cash the market has * @param borrows The total amount of borrows the market has outstanding * @param reserves The total amount of reserves the market has * @param reserveFactorMantissa The current reserve factor the market has * @return The supply rate per block (as a percentage, and scaled by 1e18) */ function getSupplyRate( uint256 cash, uint256 borrows, uint256 reserves, uint256 reserveFactorMantissa ) external view returns (uint256); } contract LevCompFactory { address public immutable original; event Cloned(address indexed clone); event Deployed(address indexed original); constructor( address _vault, address _cToken, address _router, address _comp, address _comptroller, address _weth, uint256 _secondsPerBlock ) public { Strategy _original = new Strategy( _vault, _cToken, _router, _comp, _comptroller, _weth, _secondsPerBlock ); emit Deployed(address(_original)); original = address(_original); _original.setStrategist(msg.sender); } function name() external view returns (string memory) { return string( abi.encodePacked( "Factory", Strategy(payable(original)).name(), "@", Strategy(payable(original)).apiVersion() ) ); } function cloneLevComp( address _vault, address _cToken, address _router, address _comp, address _comptroller, address _weth, uint256 _secondsPerBlock ) external returns (address payable newStrategy) { // Copied from https://github.com/optionality/clone-factory/blob/master/contracts/CloneFactory.sol bytes20 addressBytes = bytes20(original); assembly { // EIP-1167 bytecode let clone_code := mload(0x40) mstore( clone_code, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000 ) mstore(add(clone_code, 0x14), addressBytes) mstore( add(clone_code, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000 ) newStrategy := create(0, clone_code, 0x37) } Strategy(newStrategy).initialize( _vault, _cToken, _router, _comp, _comptroller, _weth, _secondsPerBlock ); Strategy(newStrategy).setRewards(msg.sender); Strategy(newStrategy).setStrategist(msg.sender); emit Cloned(newStrategy); } } /** * @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); } } /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn( token, abi.encodeWithSelector(token.transfer.selector, to, value) ); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn( token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value) ); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn( token, abi.encodeWithSelector(token.approve.selector, spender, value) ); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender).add( value ); _callOptionalReturn( token, abi.encodeWithSelector( token.approve.selector, spender, newAllowance ) ); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender).sub( value, "SafeERC20: decreased allowance below zero" ); _callOptionalReturn( token, abi.encodeWithSelector( token.approve.selector, spender, newAllowance ) ); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall( data, "SafeERC20: low-level call failed" ); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require( abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed" ); } } } /** * @dev 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; } } interface IERC20Extended is IERC20 { function decimals() external view returns (uint8); function name() external view returns (string memory); function symbol() external view returns (string memory); } contract Strategy is BaseStrategy { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; // Comptroller address for compound.finance ComptrollerI public compound; //Only three tokens we use address public comp; address public weth; CErc20I public cToken; uint256 private secondsPerBlock; //1 for fantom. 13 for ethereum IUniswapV2Router02 public currentRouter; //uni v2 forks only uint256 public collateralTarget; // total borrow / total supply ratio we are targeting (100% = 1e18) uint256 private blocksToLiquidationDangerZone; // minimum number of blocks before liquidation uint256 public minWant; // minimum amount of want to act on // Rewards handling bool public dontClaimComp; // enable/disables COMP claiming uint256 public minCompToSell; // minimum amount of COMP to be sold uint256 public iterations; //number of loops we do bool public forceMigrate; bool public withdrawChecks; bool public splitCompDistribution; constructor( address _vault, address _cToken, address _router, address _comp, address _comptroller, address _weth, uint256 _secondsPerBlock ) public BaseStrategy(_vault) { _initializeThis( _cToken, _router, _comp, _comptroller, _weth, _secondsPerBlock ); } function approveTokenMax(address token, address spender) internal { IERC20(token).safeApprove(spender, type(uint256).max); } function name() external view override returns (string memory) { return "GenLevCompV3NoFlash"; } function initialize( address _vault, address _cToken, address _router, address _comp, address _comptroller, address _weth, uint256 _secondsPerBlock ) external { _initialize(_vault, msg.sender, msg.sender, msg.sender); _initializeThis( _cToken, _router, _comp, _comptroller, _weth, _secondsPerBlock ); } function _initializeThis( address _cToken, address _router, address _comp, address _comptroller, address _weth, uint256 _secondsPerBlock ) internal { cToken = CErc20I(_cToken); comp = _comp; weth = _weth; secondsPerBlock = _secondsPerBlock; compound = ComptrollerI(_comptroller); require(IERC20Extended(address(want)).decimals() <= 18); // dev: want not supported currentRouter = IUniswapV2Router02(_router); //pre-set approvals approveTokenMax(comp, address(currentRouter)); approveTokenMax(address(want), address(cToken)); // You can set these parameters on deployment to whatever you want maxReportDelay = 86400; // once per 24 hours profitFactor = 100_000; // multiple before triggering harvest debtThreshold = 1e30; iterations = 6; //standard 6 // set minWant to 1e-5 want minWant = uint256( uint256(10)**uint256((IERC20Extended(address(want))).decimals()) ).div(1e5); minCompToSell = 0.1 ether; //may need to be changed depending on what comp is collateralTarget = 0.73 ether; blocksToLiquidationDangerZone = 46500; } /* * Control Functions */ function setWithdrawChecks(bool _withdrawChecks) external management { withdrawChecks = _withdrawChecks; } function setDontClaimComp(bool _dontClaimComp) external management { dontClaimComp = _dontClaimComp; } function setRouter(address _currentV2Router) external onlyGovernance { currentRouter = IUniswapV2Router02(_currentV2Router); } function setForceMigrate(bool _force) external onlyGovernance { forceMigrate = _force; } function setSplitCompDistribution(bool _split) external management { splitCompDistribution = _split; } function setMinCompToSell(uint256 _minCompToSell) external management { minCompToSell = _minCompToSell; } function setIterations(uint256 _iterations) external management { require(_iterations > 0 && _iterations <= 100); iterations = _iterations; } function setMinWant(uint256 _minWant) external management { minWant = _minWant; } function setCollateralTarget(uint256 _collateralTarget) external management { (, uint256 collateralFactorMantissa, ) = compound.markets( address(cToken) ); require(collateralFactorMantissa > _collateralTarget); collateralTarget = _collateralTarget; } /* * Base External Facing Functions */ /* * An accurate estimate for the total amount of assets (principle + return) * that this strategy is currently managing, denominated in terms of want tokens. */ function estimatedTotalAssets() public view override returns (uint256) { (uint256 deposits, uint256 borrows) = getCurrentPosition(); uint256 _claimableComp = predictCompAccrued(); uint256 currentComp = balanceOfToken(comp); // Use touch price. it doesnt matter if we are wrong as this is not used for decision making uint256 estimatedWant = priceCheck( comp, address(want), _claimableComp.add(currentComp) ); uint256 conservativeWant = estimatedWant.mul(9).div(10); //10% pessimist return balanceOfToken(address(want)) .add(deposits) .add(conservativeWant) .sub(borrows); } function balanceOfToken(address token) internal view returns (uint256) { return IERC20(token).balanceOf(address(this)); } //predicts our profit at next report function expectedReturn() public view returns (uint256) { uint256 estimateAssets = estimatedTotalAssets(); uint256 debt = vault.strategies(address(this)).totalDebt; if (debt > estimateAssets) { return 0; } else { return estimateAssets.sub(debt); } } /* * Provide a signal to the keeper that `tend()` should be called. * (keepers are always reimbursed by yEarn) * * NOTE: this call and `harvestTrigger` should never return `true` at the same time. * tendTrigger should be called with same gasCost as harvestTrigger */ function tendTrigger(uint256 gasCost) public view override returns (bool) { if (harvestTrigger(gasCost)) { //harvest takes priority return false; } return getblocksUntilLiquidation() <= blocksToLiquidationDangerZone; } //WARNING. manipulatable and simple routing. Only use for safe functions function priceCheck( address start, address end, uint256 _amount ) public view returns (uint256) { if (_amount == 0) { return 0; } if (start == end) { return _amount; } uint256[] memory amounts = currentRouter.getAmountsOut( _amount, getTokenOutPathV2(start, end) ); return amounts[amounts.length - 1]; } /***************** * Public non-base function ******************/ //Calculate how many blocks until we are in liquidation based on current interest rates //WARNING does not include compounding so the estimate becomes more innacurate the further ahead we look //equation. Compound doesn't include compounding for most blocks //((deposits*colateralThreshold - borrows) / (borrows*borrowrate - deposits*colateralThreshold*interestrate)); function getblocksUntilLiquidation() public view returns (uint256) { (, uint256 collateralFactorMantissa, ) = compound.markets( address(cToken) ); (uint256 deposits, uint256 borrows) = getCurrentPosition(); uint256 borrrowRate = cToken.borrowRatePerBlock(); uint256 supplyRate = cToken.supplyRatePerBlock(); uint256 collateralisedDeposit = deposits .mul(collateralFactorMantissa) .div(1e18); uint256 denom1 = borrows.mul(borrrowRate); uint256 denom2 = collateralisedDeposit.mul(supplyRate); if (denom2 >= denom1) { return type(uint256).max; } else { uint256 numer = collateralisedDeposit.sub(borrows); uint256 denom = denom1.sub(denom2); //minus 1 for this block return numer.mul(1e18).div(denom); } } // This function makes a prediction on how much comp is accrued // It is not 100% accurate as it uses current balances in Compound to predict into the past function predictCompAccrued() public view returns (uint256) { (uint256 deposits, uint256 borrows) = getCurrentPosition(); if (deposits == 0) { return 0; // should be impossible to have 0 balance and positive comp accrued } uint256 distributionPerBlockSupply; uint256 distributionPerBlockBorrow; if (splitCompDistribution) { distributionPerBlockSupply = compound.compSupplySpeeds( address(cToken) ); distributionPerBlockBorrow = compound.compBorrowSpeeds( address(cToken) ); } else { //pre 062 forks distributionPerBlockSupply = compound.compSpeeds(address(cToken)); distributionPerBlockBorrow = distributionPerBlockSupply; } uint256 totalBorrow = cToken.totalBorrows(); //total supply needs to be echanged to underlying using exchange rate uint256 totalSupplyCtoken = cToken.totalSupply(); uint256 totalSupply = totalSupplyCtoken .mul(cToken.exchangeRateStored()) .div(1e18); uint256 blockShareSupply = 0; if (totalSupply > 0) { blockShareSupply = deposits.mul(distributionPerBlockSupply).div( totalSupply ); } uint256 blockShareBorrow = 0; if (totalBorrow > 0) { blockShareBorrow = borrows.mul(distributionPerBlockBorrow).div( totalBorrow ); } //how much we expect to earn per block uint256 blockShare = blockShareSupply.add(blockShareBorrow); //last time we ran harvest uint256 lastReport = vault.strategies(address(this)).lastReport; uint256 blocksSinceLast = (block.timestamp.sub(lastReport)).div( secondsPerBlock ); return blocksSinceLast.mul(blockShare); } //Returns the current position //WARNING - this returns just the balance at last time someone touched the cToken token. Does not accrue interst in between //cToken is very active so not normally an issue. function getCurrentPosition() public view returns (uint256 deposits, uint256 borrows) { ( , uint256 ctokenBalance, uint256 borrowBalance, uint256 exchangeRate ) = cToken.getAccountSnapshot(address(this)); borrows = borrowBalance; deposits = ctokenBalance.mul(exchangeRate).div(1e18); } //statechanging version function getLivePosition() public returns (uint256 deposits, uint256 borrows) { deposits = cToken.balanceOfUnderlying(address(this)); //we can use non state changing now because we updated state with balanceOfUnderlying call borrows = cToken.borrowBalanceStored(address(this)); } //Same warning as above function netBalanceLent() public view returns (uint256) { (uint256 deposits, uint256 borrows) = getCurrentPosition(); return deposits.sub(borrows); } /*********** * internal core logic *********** */ /* * A core method. * Called at beggining of harvest before providing report to owner * 1 - claim accrued comp * 2 - if enough to be worth it we sell * 3 - because we lose money on our loans we need to offset profit from comp. */ function prepareReturn(uint256 _debtOutstanding) internal override returns ( uint256 _profit, uint256 _loss, uint256 _debtPayment ) { _profit = 0; _loss = 0; // for clarity. also reduces bytesize if (balanceOfToken(address(cToken)) == 0) { uint256 wantBalance = balanceOfToken(address(want)); //no position to harvest //but we may have some debt to return //it is too expensive to free more debt in this method so we do it in adjust position _debtPayment = Math.min(wantBalance, _debtOutstanding); return (_profit, _loss, _debtPayment); } (uint256 deposits, uint256 borrows) = getLivePosition(); //claim comp accrued _claimComp(); //sell comp _disposeOfComp(); uint256 wantBalance = balanceOfToken(address(want)); uint256 investedBalance = deposits.sub(borrows); uint256 balance = investedBalance.add(wantBalance); uint256 debt = vault.strategies(address(this)).totalDebt; //Balance - Total Debt is profit if (balance > debt) { _profit = balance.sub(debt); if (wantBalance < _profit) { //all reserve is profit _profit = wantBalance; } else if (wantBalance > _profit.add(_debtOutstanding)) { _debtPayment = _debtOutstanding; } else { _debtPayment = wantBalance.sub(_profit); } } else { //we will lose money until we claim comp then we will make money //this has an unintended side effect of slowly lowering our total debt allowed _loss = debt.sub(balance); _debtPayment = Math.min(wantBalance, _debtOutstanding); } } /* * Second core function. Happens after report call. * * Similar to deposit function from V1 strategy */ function adjustPosition(uint256 _debtOutstanding) internal override { //emergency exit is dealt with in prepareReturn if (emergencyExit) { return; } //we are spending all our cash unless we have debt outstanding uint256 _wantBal = balanceOfToken(address(want)); if (_wantBal < _debtOutstanding) { //this is graceful withdrawal. dont use backup //we use more than 1 because withdrawunderlying causes problems with 1 token due to different decimals if (balanceOfToken(address(cToken)) > 1) { _withdrawSome(_debtOutstanding.sub(_wantBal)); } return; } (uint256 position, bool deficit) = _calculateDesiredPosition( _wantBal.sub(_debtOutstanding), true ); //if we are below minimun want change it is not worth doing //need to be careful in case this pushes to liquidation uint256 i = 0; while (position > minWant) { position = position.sub(_noFlashLoan(position, deficit)); if (i >= iterations) { break; } i++; } } /************* * Very important function * Input: amount we want to withdraw * cannot be more than we have * Returns amount we were able to withdraw. notall if user has some balance left * * Deleverage position -> redeem our cTokens ******************** */ function _withdrawSome(uint256 _amount) internal returns (bool notAll) { (uint256 position, bool deficit) = _calculateDesiredPosition( _amount, false ); //If there is no deficit we dont need to adjust position //if the position change is tiny do nothing if (deficit && position > minWant) { uint8 i = 0; //position will equal 0 unless we haven't been able to deleverage enough with flash loan //if we are not in deficit we dont need to do flash loan while (position > minWant.add(100)) { position = position.sub(_noFlashLoan(position, true)); i++; //A limit set so we don't run out of gas if (i >= iterations) { notAll = true; break; } } } //now withdraw //if we want too much we just take max //This part makes sure our withdrawal does not force us into liquidation (uint256 depositBalance, uint256 borrowBalance) = getCurrentPosition(); uint256 tempColla = collateralTarget; uint256 reservedAmount = 0; if (tempColla == 0) { tempColla = 1e15; // 0.001 * 1e18. lower we have issues } reservedAmount = borrowBalance.mul(1e18).div(tempColla); if (depositBalance >= reservedAmount) { uint256 redeemable = depositBalance.sub(reservedAmount); uint256 balan = cToken.balanceOf(address(this)); if (balan > 1) { if (redeemable < _amount) { cToken.redeemUnderlying(redeemable); } else { cToken.redeemUnderlying(_amount); } } } if ( collateralTarget == 0 && balanceOfToken(address(want)) > borrowBalance ) { cToken.repayBorrow(borrowBalance); } } /*********** * This is the main logic for calculating how to change our lends and borrows * Input: balance. The net amount we are going to deposit/withdraw. * Input: dep. Is it a deposit or withdrawal * Output: position. The amount we want to change our current borrow position. * Output: deficit. True if we are reducing position size * * For instance deficit =false, position 100 means increase borrowed balance by 100 ****** */ function _calculateDesiredPosition(uint256 balance, bool dep) internal returns (uint256 position, bool deficit) { //we want to use statechanging for safety (uint256 deposits, uint256 borrows) = getLivePosition(); //When we unwind we end up with the difference between borrow and supply uint256 unwoundDeposit = deposits.sub(borrows); //we want to see how close to collateral target we are. //So we take our unwound deposits and add or remove the balance we are are adding/removing. //This gives us our desired future undwoundDeposit (desired supply) uint256 desiredSupply = 0; if (dep) { desiredSupply = unwoundDeposit.add(balance); } else { if (balance > unwoundDeposit) { balance = unwoundDeposit; } desiredSupply = unwoundDeposit.sub(balance); } //(ds *c)/(1-c) uint256 num = desiredSupply.mul(collateralTarget); uint256 den = uint256(1e18).sub(collateralTarget); uint256 desiredBorrow = num.div(den); if (desiredBorrow > 1e5) { //stop us going right up to the wire desiredBorrow = desiredBorrow.sub(1e5); } //now we see if we want to add or remove balance // if the desired borrow is less than our current borrow we are in deficit. so we want to reduce position if (desiredBorrow < borrows) { deficit = true; position = borrows.sub(desiredBorrow); //safemath check done in if statement } else { //otherwise we want to increase position deficit = false; position = desiredBorrow.sub(borrows); } } /* * Liquidate as many assets as possible to `want`, irregardless of slippage, * up to `_amount`. Any excess should be re-invested here as well. */ function liquidatePosition(uint256 _amountNeeded) internal override returns (uint256 _amountFreed, uint256 _loss) { uint256 _balance = balanceOfToken(address(want)); uint256 assets = netBalanceLent().add(_balance); (uint256 deposits, uint256 borrows) = getLivePosition(); if (assets < _amountNeeded) { //if we cant afford to withdraw we take all we can //withdraw all we can //1 token causes rounding error with withdrawUnderlying if (balanceOfToken(address(cToken)) > 1) { _withdrawSome(deposits.sub(borrows)); } _amountFreed = Math.min( _amountNeeded, balanceOfToken(address(want)) ); } else { if (_balance < _amountNeeded) { _withdrawSome(_amountNeeded.sub(_balance)); //overflow error if we return more than asked for _amountFreed = Math.min( _amountNeeded, balanceOfToken(address(want)) ); } else { _amountFreed = _amountNeeded; } } // To prevent the vault from moving on to the next strategy in the queue // when we return the amountRequested minus dust, take a dust sized loss if (_amountFreed < _amountNeeded) { uint256 diff = _amountNeeded.sub(_amountFreed); if (diff <= minWant) { _loss = diff; } } if (withdrawChecks) { require(_amountNeeded == _amountFreed.add(_loss)); // dev: fourThreeProtection } } function _claimComp() internal { if (dontClaimComp) { return; } CTokenI[] memory tokens = new CTokenI[](1); tokens[0] = cToken; compound.claimComp(address(this), tokens); } //sell comp function function _disposeOfComp() internal { uint256 _comp = balanceOfToken(comp); if (_comp < minCompToSell) { return; } currentRouter.swapExactTokensForTokens( _comp, 0, getTokenOutPathV2(comp, address(want)), address(this), now ); } function getTokenOutPathV2(address _tokenIn, address _tokenOut) internal view returns (address[] memory _path) { bool isWeth = _tokenIn == address(weth) || _tokenOut == address(weth); _path = new address[](isWeth ? 2 : 3); _path[0] = _tokenIn; if (isWeth) { _path[1] = _tokenOut; } else { _path[1] = address(weth); _path[2] = _tokenOut; } } //lets leave //if we can't deleverage in one go set collateralFactor to 0 and call harvest multiple times until delevered function prepareMigration(address _newStrategy) internal override { if (!forceMigrate) { (uint256 deposits, uint256 borrows) = getLivePosition(); _withdrawSome(deposits.sub(borrows)); (, , uint256 borrowBalance, ) = cToken.getAccountSnapshot( address(this) ); require(borrowBalance < 10_000); IERC20 _comp = IERC20(comp); uint256 _compB = balanceOfToken(address(_comp)); if (_compB > 0) { _comp.safeTransfer(_newStrategy, _compB); } } } //Three functions covering normal leverage and deleverage situations // max is the max amount we want to increase our borrowed balance // returns the amount we actually did function _noFlashLoan(uint256 max, bool deficit) internal returns (uint256 amount) { //we can use non-state changing because this function is always called after _calculateDesiredPosition (uint256 lent, uint256 borrowed) = getCurrentPosition(); //if we have nothing borrowed then we can't deleverage any more if (borrowed == 0 && deficit) { return 0; } if (lent == 0) { cToken.mint(balanceOfToken(address(want))); (lent, borrowed) = getCurrentPosition(); } (, uint256 collateralFactorMantissa, ) = compound.markets( address(cToken) ); if (deficit) { amount = _normalDeleverage( max, lent, borrowed, collateralFactorMantissa ); } else { amount = _normalLeverage( max, lent, borrowed, collateralFactorMantissa ); } } //maxDeleverage is how much we want to reduce by function _normalDeleverage( uint256 maxDeleverage, uint256 lent, uint256 borrowed, uint256 collatRatio ) internal returns (uint256 deleveragedAmount) { uint256 theoreticalLent = 0; //collat ration should never be 0. if it is something is very wrong... but just incase if (collatRatio != 0) { theoreticalLent = borrowed.mul(1e18).div(collatRatio); } deleveragedAmount = lent.sub(theoreticalLent); if (deleveragedAmount >= borrowed) { deleveragedAmount = borrowed; } if (deleveragedAmount >= maxDeleverage) { deleveragedAmount = maxDeleverage; } uint256 exchangeRateStored = cToken.exchangeRateStored(); //redeemTokens = redeemAmountIn * 1e18 / exchangeRate. must be more than 0 //a rounding error means we need another small addition if ( deleveragedAmount.mul(1e18) >= exchangeRateStored && deleveragedAmount > 10 ) { deleveragedAmount = deleveragedAmount.sub(uint256(10)); cToken.redeemUnderlying(deleveragedAmount); //our borrow has been increased by no more than maxDeleverage cToken.repayBorrow(deleveragedAmount); } } //maxDeleverage is how much we want to increase by function _normalLeverage( uint256 maxLeverage, uint256 lent, uint256 borrowed, uint256 collatRatio ) internal returns (uint256 leveragedAmount) { uint256 theoreticalBorrow = lent.mul(collatRatio).div(1e18); leveragedAmount = theoreticalBorrow.sub(borrowed); if (leveragedAmount >= maxLeverage) { leveragedAmount = maxLeverage; } if (leveragedAmount > 10) { leveragedAmount = leveragedAmount.sub(uint256(10)); cToken.borrow(leveragedAmount); cToken.mint(balanceOfToken(address(want))); } } //emergency function that we can use to deleverage manually if something is broken function manualDeleverage(uint256 amount) external management { require(cToken.redeemUnderlying(amount) == 0); require(cToken.repayBorrow(amount) == 0); } //emergency function that we can use to deleverage manually if something is broken function manualReleaseWant(uint256 amount) external onlyGovernance { require(cToken.redeemUnderlying(amount) == 0); // dev: !manual-release-want } function protectedTokens() internal view override returns (address[] memory) {} //returns our current collateralisation ratio. Should be compared with collateralTarget function storedCollateralisation() public view returns (uint256 collat) { (uint256 lend, uint256 borrow) = getCurrentPosition(); if (lend == 0) { return 0; } collat = uint256(1e18).mul(borrow).div(lend); } // -- Internal Helper functions -- // function ethToWant(uint256 _amtInWei) public view override returns (uint256) { return priceCheck(weth, address(want), _amtInWei); } function liquidateAllPositions() internal override returns (uint256 _amountFreed) { (_amountFreed, ) = liquidatePosition(vault.debtOutstanding()); (uint256 deposits, uint256 borrows) = getCurrentPosition(); uint256 position = deposits.sub(borrows); //we want to revert if we can't liquidateall if (!forceMigrate) { require(position < minWant); } } function mgtm_check() internal view { require( msg.sender == governance() || msg.sender == vault.management() || msg.sender == strategist, "!authorized" ); } modifier management() { mgtm_check(); _; } }
number of loops we do
uint256 public iterations;
12,945,562
[ 1, 2696, 434, 14075, 732, 741, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 5034, 1071, 11316, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
//Address: 0x25e3d9ed8f5c06f2b4d334294986894810619309 //Contract name: PriIcoSale2 //Balance: 0 Ether //Verification Date: 5/29/2018 //Transacion Count: 5 // CODE STARTS HERE pragma solidity 0.4.24; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { 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) { return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } /** * @title Token * @dev Implemented token interface */ contract Token { function transferSoldToken(address _contractAddr, address _to, uint256 _value) public returns(bool); function balanceOf(address who) public view returns (uint256); function totalSupply() public view returns (uint256); } contract WhiteList { function register(address _address) public; function unregister(address _address) public; function isRegistered(address _address) public view returns(bool); } /** * @title BtradeIcoSale * @dev Smart contract for ico sale */ contract PriIcoSale2 { using SafeMath for uint256; // use SafeMath address public owner; // BtradeIcoSale creator address public beneficiary; // After ico end, send to address uint public fundingEthGoal; // Goal funding ethereum amount uint public raisedEthAmt; // Funded ethereum amout uint public totalSoldTokenCount; // Sold total token count uint public pricePerEther; // Percentage of token per ethereum Token public tokenReward; // ERC20 based token address WhiteList public whiteListMge; // Whitelist manage contract address bool enableWhiteList = false; // check whitelist flag bool public icoProceeding = false; // Whether ico is in progress mapping(address => uint256) public funderEthAmt; event ResistWhiteList(address funder, bool isRegist); // white list resist event event UnregisteWhiteList(address funder, bool isRegist); // white list remove event event FundTransfer(address backer, uint amount, bool isContribution); // Investment Event event StartICO(address owner, bool isStart); event CloseICO(address recipient, uint totalAmountRaised); // ico close event event ReturnExcessAmount(address funder, uint amount); /** * Constructor function * Setup the owner */ function PriIcoSale2(address _sendAddress, uint _goalEthers, uint _dividendRate, address _tokenAddress, address _whiteListAddress) public { require(_sendAddress != address(0)); require(_tokenAddress != address(0)); require(_whiteListAddress != address(0)); owner = msg.sender; // set owner beneficiary = _sendAddress; // set beneficiary fundingEthGoal = _goalEthers * 1 ether; // set goal ethereu pricePerEther = _dividendRate; // set price per ether tokenReward = Token(_tokenAddress); // set token address whiteListMge = WhiteList(_whiteListAddress); // set whitelist address } /** * Start ICO crowdsale. */ function startIco() public { require(msg.sender == owner); require(!icoProceeding); icoProceeding = true; emit StartICO(msg.sender, true); } /** * Close ICO crowdsale. */ function endIco() public { require(msg.sender == owner); require(icoProceeding); icoProceeding = false; emit CloseICO(beneficiary, raisedEthAmt); } /** * Check whiteList. */ function setEnableWhiteList(bool _flag) public { require(msg.sender == owner); require(enableWhiteList != _flag); enableWhiteList = _flag; } /** * Resist White list for to fund * @param _funderAddress the address of the funder */ function resistWhiteList(address _funderAddress) public { require(msg.sender == owner); require(_funderAddress != address(0)); require(!whiteListMge.isRegistered(_funderAddress)); whiteListMge.register(_funderAddress); emit ResistWhiteList(_funderAddress, true); } function removeWhiteList(address _funderAddress) public { require(msg.sender == owner); require(_funderAddress != address(0)); require(whiteListMge.isRegistered(_funderAddress)); whiteListMge.unregister(_funderAddress); emit UnregisteWhiteList(_funderAddress, false); } /** * Fallback function * The function without name is the default function that is called whenever anyone sends funds to a contract */ function () public payable { require(icoProceeding); require(raisedEthAmt < fundingEthGoal); require(msg.value >= 0.1 ether); // Minimum deposit amount if (enableWhiteList) { require(whiteListMge.isRegistered(msg.sender)); } uint amount = msg.value; // Deposit amount uint remainToGoal = fundingEthGoal - raisedEthAmt; uint returnAmt = 0; // Amount to return when the goal is exceeded if (remainToGoal < amount) { returnAmt = msg.value.sub(remainToGoal); amount = remainToGoal; } // Token quantity calculation and token transfer, if excess amount is exceeded, it is sent to investor uint tokenCount = amount.mul(pricePerEther); if (tokenReward.transferSoldToken(address(this), msg.sender, tokenCount)) { raisedEthAmt = raisedEthAmt.add(amount); totalSoldTokenCount = totalSoldTokenCount.add(tokenCount); funderEthAmt[msg.sender] = funderEthAmt[msg.sender].add(amount); emit FundTransfer(msg.sender, amount, true); // The amount above the target amount is returned. if (returnAmt > 0) { msg.sender.transfer(returnAmt); icoProceeding = false; // ICO close emit ReturnExcessAmount(msg.sender, returnAmt); } } } /** * Check if goal was reached * * Checks if the goal or time limit has been reached and ends the campaign */ function checkGoalReached() public { require(msg.sender == owner); if (raisedEthAmt >= fundingEthGoal){ safeWithdrawal(); } icoProceeding = false; } /** * Withdraw the funds */ function safeWithdrawal() public { require(msg.sender == owner); beneficiary.transfer(address(this).balance); emit FundTransfer(beneficiary, address(this).balance, false); } }
white list resist event
event ResistWhiteList(address funder, bool isRegist);
2,558,692
[ 1, 14739, 666, 400, 376, 871, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 871, 1124, 376, 13407, 682, 12, 2867, 284, 9341, 16, 1426, 353, 1617, 376, 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 ]
/** *Submitted for verification at Etherscan.io on 2021-11-15 */ // SPDX-License-Identifier: BSD-3-Clause // File: contracts/interfaces/IOwner.sol pragma solidity 0.8.4; /** * @title BiFi-Bifrost-Extension IOwner Interface * @notice Interface for Owner Contract * @author BiFi-Bifrost-Extension(seinmyung25, Miller-kk, tlatkdgus1, dongchangYoo) */ interface IOwner { function transferOwnership(address _owner) external; function acceptOwnership() external; function setOwner(address _owner) external; function setAdmin(address _admin, uint256 auth) external; } // File: contracts/libs/Owner.sol pragma solidity 0.8.4; abstract contract Owner is IOwner { address payable public owner; address payable public pendingOwner; mapping(address => uint256) public admins; modifier onlyOwner() { require(payable( msg.sender ) == owner, "only Owner"); _; } modifier onlyAdmin() { address payable sender = payable( msg.sender ); require(sender == owner || admins[sender] != 0, "only Admin"); _; } constructor() { admins[owner = payable( msg.sender )] = 1; } function transferOwnership(address _nextOwner) override external onlyOwner { pendingOwner = payable( _nextOwner ); } function acceptOwnership() override external { address payable sender = payable( msg.sender ); require(sender == pendingOwner, "pendingOwner"); owner = sender; } function setOwner(address _nextOwner) override external onlyOwner { owner = payable( _nextOwner ); } function setAdmin(address _admin, uint256 auth) override external onlyOwner { admins[_admin] = auth; } } // File: contracts/libs/proxy/ProxyStorage.sol pragma solidity 0.8.4; /** * @title BiFi-Bifrost-Extension ProxyStorage Contract * @notice Contract for proxy storage layout sharing * @author BiFi-Bifrost-Extension(seinmyung25, Miller-kk, tlatkdgus1, dongchangYoo) */ abstract contract ProxyStorage is Owner { address public _implement; } // File: contracts/interfaces/IERC20.sol pragma solidity 0.8.4; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { function mint(address to, uint256 amount) external returns (bool); function burn(uint256 amount) external returns (bool); function burnFrom(address from, uint256 amount) external returns (bool); /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: contracts/libs/IERC20Metadata.sol pragma solidity 0.8.4; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // File: contracts/libs/utils/Context.sol pragma solidity 0.8.4; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: contracts/libs/ERC20.sol pragma solidity 0.8.4; /** * @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}. */ abstract contract ERC20 is Context, IERC20, IERC20Metadata { mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @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_; // } function _init(string memory name_, string memory symbol_, uint8 decimals_) internal returns (bool) { _name = name_; _symbol = symbol_; _decimals = decimals_; return true; } /** * @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 _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); _approve(sender, _msgSender(), currentAllowance - amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); _approve(_msgSender(), spender, currentAllowance - subtractedValue); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); _balances[sender] = senderBalance - amount; _balances[recipient] += amount; emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); _balances[account] = accountBalance - amount; _totalSupply -= amount; emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // File: contracts/libs/ERC20Burnable.sol pragma solidity 0.8.4; /** * @dev Extension of {ERC20} that allows token holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ contract ERC20Burnable is Owner, Context, ERC20 { function init(string memory name_, string memory symbol_, uint8 decimals_) onlyAdmin external returns (bool) { return _init(name_, symbol_, decimals_); } function mint(address user, uint256 amount) onlyAdmin override external returns (bool) { _mint(user, amount); return true; } /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) override public virtual returns (bool) { _burn(_msgSender(), amount); return true; } /** * @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) override public virtual returns (bool) { uint256 currentAllowance = allowance(account, _msgSender()); require(currentAllowance >= amount, "ERC20: burn amount exceeds allowance"); _approve(account, _msgSender(), currentAllowance - amount); _burn(account, amount); return true; } } // File: contracts/deploy/BifrostBTC.sol pragma solidity 0.8.4; /** * @title BiFi-Bifrost-Extension "tokenName" Contract * @notice Contract for "tokenName" deployment * @author BiFi-Bifrost-Extension(seinmyung25, Miller-kk, tlatkdgus1, dongchangYoo) */ contract BifrostBTC is ERC20Burnable { constructor() { owner = payable(msg.sender); _init('BifrostBTC', 'BiBTC', 8); } }
* @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) override public virtual returns (bool) { uint256 currentAllowance = allowance(account, _msgSender()); require(currentAllowance >= amount, "ERC20: burn amount exceeds allowance"); _approve(account, _msgSender(), currentAllowance - amount); _burn(account, amount); return true; }
10,896,096
[ 1, 9378, 28599, 1375, 8949, 68, 2430, 628, 1375, 4631, 9191, 11140, 853, 310, 628, 326, 4894, 1807, 1699, 1359, 18, 2164, 288, 654, 39, 3462, 17, 67, 70, 321, 97, 471, 288, 654, 39, 3462, 17, 5965, 1359, 5496, 29076, 30, 300, 326, 4894, 1297, 1240, 1699, 1359, 364, 12176, 13739, 10335, 11, 87, 2430, 434, 622, 4520, 1375, 8949, 8338, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 18305, 1265, 12, 2867, 2236, 16, 2254, 5034, 3844, 13, 3849, 1071, 5024, 1135, 261, 6430, 13, 288, 203, 3639, 2254, 5034, 783, 7009, 1359, 273, 1699, 1359, 12, 4631, 16, 389, 3576, 12021, 10663, 203, 3639, 2583, 12, 2972, 7009, 1359, 1545, 3844, 16, 315, 654, 39, 3462, 30, 18305, 3844, 14399, 1699, 1359, 8863, 203, 3639, 389, 12908, 537, 12, 4631, 16, 389, 3576, 12021, 9334, 783, 7009, 1359, 300, 3844, 1769, 203, 3639, 389, 70, 321, 12, 4631, 16, 3844, 1769, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: Apache-2.0 /** * Authors: Moonstream Engineering (engineering@moonstream.to) * GitHub: https://github.com/bugout-dev/dao * * An ERC1155 implementation which uses the Moonstream DAO common storage structure for proxies. * EIP1155: https://eips.ethereum.org/EIPS/eip-1155 * * The Moonstream contract is used to delegate calls from an EIP2535 Diamond proxy. * * This implementation is adapted from the OpenZeppelin ERC1155 implementation: * https://github.com/OpenZeppelin/openzeppelin-contracts/tree/6bd6b76d1156e20e45d1016f355d154141c7e5b9/contracts/token/ERC1155 */ pragma solidity ^0.8.9; import "@openzeppelin-contracts/contracts/token/ERC1155/IERC1155.sol"; import "@openzeppelin-contracts/contracts/token/ERC1155/IERC1155Receiver.sol"; import "@openzeppelin-contracts/contracts/token/ERC1155/extensions/IERC1155MetadataURI.sol"; import "@openzeppelin-contracts/contracts/utils/Address.sol"; import "@openzeppelin-contracts/contracts/utils/Context.sol"; import "@openzeppelin-contracts/contracts/utils/introspection/ERC165.sol"; import "./LibTerminus.sol"; contract ERC1155WithTerminusStorage is Context, ERC165, IERC1155, IERC1155MetadataURI { using Address for address; constructor() {} /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC1155).interfaceId || interfaceId == type(IERC1155MetadataURI).interfaceId || super.supportsInterface(interfaceId); } function uri(uint256 poolID) public view virtual override returns (string memory) { return LibTerminus.terminusStorage().poolURI[poolID]; } /** * @dev See {IERC1155-balanceOf}. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) public view virtual override returns (uint256) { require( account != address(0), "ERC1155WithTerminusStorage: balance query for the zero address" ); return LibTerminus.terminusStorage().poolBalances[id][account]; } /** * @dev See {IERC1155-balanceOfBatch}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] memory accounts, uint256[] memory ids) public view virtual override returns (uint256[] memory) { require( accounts.length == ids.length, "ERC1155WithTerminusStorage: accounts and ids length mismatch" ); uint256[] memory batchBalances = new uint256[](accounts.length); for (uint256 i = 0; i < accounts.length; ++i) { batchBalances[i] = balanceOf(accounts[i], ids[i]); } return batchBalances; } /** * @dev See {IERC1155-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC1155-isApprovedForAll}. */ function isApprovedForAll(address account, address operator) public view virtual override returns (bool) { return LibTerminus.terminusStorage().globalOperatorApprovals[account][ operator ]; } function isApprovedForPool(uint256 poolID, address operator) public view returns (bool) { return LibTerminus._isApprovedForPool(poolID, operator); } function approveForPool(uint256 poolID, address operator) external { LibTerminus.enforcePoolIsController(poolID, _msgSender()); LibTerminus._approveForPool(poolID, operator); } /** * @dev See {IERC1155-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) public virtual override { require( from == _msgSender() || isApprovedForAll(from, _msgSender()) || isApprovedForPool(id, _msgSender()), "ERC1155WithTerminusStorage: caller is not owner nor approved" ); _safeTransferFrom(from, to, id, amount, data); } /** * @dev See {IERC1155-safeBatchTransferFrom}. */ function safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) public virtual override { require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155WithTerminusStorage: transfer caller is not owner nor approved" ); _safeBatchTransferFrom(from, to, ids, amounts, data); } /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) internal virtual { require( to != address(0), "ERC1155WithTerminusStorage: transfer to the zero address" ); LibTerminus.TerminusStorage storage ts = LibTerminus.terminusStorage(); require( !ts.poolNotTransferable[id], "ERC1155WithTerminusStorage: _safeTransferFrom -- pool is not transferable" ); address operator = _msgSender(); _beforeTokenTransfer( operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data ); uint256 fromBalance = ts.poolBalances[id][from]; require( fromBalance >= amount, "ERC1155WithTerminusStorage: insufficient balance for transfer" ); unchecked { ts.poolBalances[id][from] = fromBalance - amount; } ts.poolBalances[id][to] += amount; emit TransferSingle(operator, from, to, id, amount); _doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require( ids.length == amounts.length, "ERC1155WithTerminusStorage: ids and amounts length mismatch" ); require( to != address(0), "ERC1155WithTerminusStorage: transfer to the zero address" ); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, ids, amounts, data); LibTerminus.TerminusStorage storage ts = LibTerminus.terminusStorage(); for (uint256 i = 0; i < ids.length; ++i) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 fromBalance = ts.poolBalances[id][from]; require( fromBalance >= amount, "ERC1155WithTerminusStorage: insufficient balance for transfer" ); unchecked { ts.poolBalances[id][from] = fromBalance - amount; } ts.poolBalances[id][to] += amount; } emit TransferBatch(operator, from, to, ids, amounts); _doSafeBatchTransferAcceptanceCheck( operator, from, to, ids, amounts, data ); } /** * @dev Creates `amount` tokens of token type `id`, and assigns them to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _mint( address to, uint256 id, uint256 amount, bytes memory data ) internal virtual { require( to != address(0), "ERC1155WithTerminusStorage: mint to the zero address" ); LibTerminus.TerminusStorage storage ts = LibTerminus.terminusStorage(); require( ts.poolSupply[id] + amount <= ts.poolCapacity[id], "ERC1155WithTerminusStorage: _mint -- Minted tokens would exceed pool capacity" ); address operator = _msgSender(); _beforeTokenTransfer( operator, address(0), to, _asSingletonArray(id), _asSingletonArray(amount), data ); ts.poolSupply[id] += amount; ts.poolBalances[id][to] += amount; emit TransferSingle(operator, address(0), to, id, amount); _doSafeTransferAcceptanceCheck( operator, address(0), to, id, amount, data ); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _mintBatch( address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require( to != address(0), "ERC1155WithTerminusStorage: mint to the zero address" ); require( ids.length == amounts.length, "ERC1155WithTerminusStorage: ids and amounts length mismatch" ); LibTerminus.TerminusStorage storage ts = LibTerminus.terminusStorage(); for (uint256 i = 0; i < ids.length; i++) { require( ts.poolSupply[ids[i]] + amounts[i] <= ts.poolCapacity[ids[i]], "ERC1155WithTerminusStorage: _mintBatch -- Minted tokens would exceed pool capacity" ); } address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), to, ids, amounts, data); for (uint256 i = 0; i < ids.length; i++) { ts.poolSupply[ids[i]] += amounts[i]; ts.poolBalances[ids[i]][to] += amounts[i]; } emit TransferBatch(operator, address(0), to, ids, amounts); _doSafeBatchTransferAcceptanceCheck( operator, address(0), to, ids, amounts, data ); } /** * @dev Destroys `amount` tokens of token type `id` from `from` * * Requirements: * * - `from` cannot be the zero address. * - `from` must have at least `amount` tokens of token type `id`. */ function _burn( address from, uint256 id, uint256 amount ) internal virtual { require( from != address(0), "ERC1155WithTerminusStorage: burn from the zero address" ); LibTerminus.TerminusStorage storage ts = LibTerminus.terminusStorage(); require( ts.poolBurnable[id], "ERC1155WithTerminusStorage: _burn -- pool is not burnable" ); address operator = _msgSender(); _beforeTokenTransfer( operator, from, address(0), _asSingletonArray(id), _asSingletonArray(amount), "" ); uint256 fromBalance = ts.poolBalances[id][from]; require( fromBalance >= amount, "ERC1155WithTerminusStorage: burn amount exceeds balance" ); unchecked { ts.poolBalances[id][from] = fromBalance - amount; ts.poolSupply[id] -= amount; } emit TransferSingle(operator, from, address(0), id, amount); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}. * * Requirements: * * - `ids` and `amounts` must have the same length. */ function _burnBatch( address from, uint256[] memory ids, uint256[] memory amounts ) internal virtual { require( from != address(0), "ERC1155WithTerminusStorage: burn from the zero address" ); require( ids.length == amounts.length, "ERC1155WithTerminusStorage: ids and amounts length mismatch" ); address operator = _msgSender(); LibTerminus.TerminusStorage storage ts = LibTerminus.terminusStorage(); for (uint256 i = 0; i < ids.length; i++) { require( ts.poolBurnable[ids[i]], "ERC1155WithTerminusStorage: _burnBatch -- pool is not burnable" ); } _beforeTokenTransfer(operator, from, address(0), ids, amounts, ""); for (uint256 i = 0; i < ids.length; i++) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 fromBalance = ts.poolBalances[id][from]; require( fromBalance >= amount, "ERC1155WithTerminusStorage: burn amount exceeds balance" ); unchecked { ts.poolBalances[id][from] = fromBalance - amount; ts.poolSupply[id] -= amount; } } emit TransferBatch(operator, from, address(0), ids, amounts); } /** * @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, "ERC1155WithTerminusStorage: setting approval status for self" ); LibTerminus.TerminusStorage storage ts = LibTerminus.terminusStorage(); ts.globalOperatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Hook that is called before any token transfer. This includes minting * and burning, as well as batched variants. * * The same hook is called on both single and batched variants. For single * transfers, the length of the `id` and `amount` arrays will be 1. * * Calling conditions (for each `id` and `amount` pair): * * - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens * of token type `id` will be transferred to `to`. * - When `from` is zero, `amount` tokens of token type `id` will be minted * for `to`. * - when `to` is zero, `amount` of ``from``'s tokens of token type `id` * will be burned. * - `from` and `to` are never both zero. * - `ids` and `amounts` have the same, non-zero length. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual {} function _doSafeTransferAcceptanceCheck( address operator, address from, address to, uint256 id, uint256 amount, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155Received( operator, from, id, amount, data ) returns (bytes4 response) { if (response != IERC1155Receiver.onERC1155Received.selector) { revert( "ERC1155WithTerminusStorage: ERC1155Receiver rejected tokens" ); } } catch Error(string memory reason) { revert(reason); } catch { revert( "ERC1155WithTerminusStorage: transfer to non ERC1155Receiver implementer" ); } } } function _doSafeBatchTransferAcceptanceCheck( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155BatchReceived( operator, from, ids, amounts, data ) returns (bytes4 response) { if ( response != IERC1155Receiver.onERC1155BatchReceived.selector ) { revert( "ERC1155WithTerminusStorage: ERC1155Receiver rejected tokens" ); } } catch Error(string memory reason) { revert(reason); } catch { revert( "ERC1155WithTerminusStorage: transfer to non ERC1155Receiver implementer" ); } } } function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) { uint256[] memory array = new uint256[](1); array[0] = element; return array; } }
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}. Requirements: - `ids` and `amounts` must have the same length./
function _burnBatch( address from, uint256[] memory ids, uint256[] memory amounts ) internal virtual { require( from != address(0), "ERC1155WithTerminusStorage: burn from the zero address" ); require( ids.length == amounts.length, "ERC1155WithTerminusStorage: ids and amounts length mismatch" ); address operator = _msgSender(); LibTerminus.TerminusStorage storage ts = LibTerminus.terminusStorage(); for (uint256 i = 0; i < ids.length; i++) { require( ts.poolBurnable[ids[i]], "ERC1155WithTerminusStorage: _burnBatch -- pool is not burnable" ); } _beforeTokenTransfer(operator, from, address(0), ids, amounts, ""); for (uint256 i = 0; i < ids.length; i++) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 fromBalance = ts.poolBalances[id][from]; require( fromBalance >= amount, "ERC1155WithTerminusStorage: burn amount exceeds balance" ); unchecked { ts.poolBalances[id][from] = fromBalance - amount; ts.poolSupply[id] -= amount; } } emit TransferBatch(operator, from, address(0), ids, amounts); }
1,796,036
[ 1, 22044, 30, 9185, 30, 12610, 2499, 2539, 18, 4539, 5303, 17, 17542, 63, 4497, 329, 65, 1177, 434, 288, 67, 70, 321, 5496, 29076, 30, 300, 1375, 2232, 68, 471, 1375, 8949, 87, 68, 1297, 1240, 326, 1967, 769, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 70, 321, 4497, 12, 203, 3639, 1758, 628, 16, 203, 3639, 2254, 5034, 8526, 3778, 3258, 16, 203, 3639, 2254, 5034, 8526, 3778, 30980, 203, 565, 262, 2713, 5024, 288, 203, 3639, 2583, 12, 203, 5411, 628, 480, 1758, 12, 20, 3631, 203, 5411, 315, 654, 39, 2499, 2539, 1190, 27506, 407, 3245, 30, 18305, 628, 326, 3634, 1758, 6, 203, 3639, 11272, 203, 3639, 2583, 12, 203, 5411, 3258, 18, 2469, 422, 30980, 18, 2469, 16, 203, 5411, 315, 654, 39, 2499, 2539, 1190, 27506, 407, 3245, 30, 3258, 471, 30980, 769, 13484, 6, 203, 3639, 11272, 203, 203, 3639, 1758, 3726, 273, 389, 3576, 12021, 5621, 203, 203, 3639, 10560, 27506, 407, 18, 27506, 407, 3245, 2502, 3742, 273, 10560, 27506, 407, 18, 9505, 407, 3245, 5621, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 3258, 18, 2469, 31, 277, 27245, 288, 203, 5411, 2583, 12, 203, 7734, 3742, 18, 6011, 38, 321, 429, 63, 2232, 63, 77, 65, 6487, 203, 7734, 315, 654, 39, 2499, 2539, 1190, 27506, 407, 3245, 30, 389, 70, 321, 4497, 1493, 2845, 353, 486, 18305, 429, 6, 203, 5411, 11272, 203, 3639, 289, 203, 203, 3639, 389, 5771, 1345, 5912, 12, 9497, 16, 628, 16, 1758, 12, 20, 3631, 3258, 16, 30980, 16, 1408, 1769, 203, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 3258, 18, 2469, 31, 277, 27245, 288, 203, 5411, 2254, 5034, 612, 273, 3258, 63, 77, 15533, 203, 5411, 2254, 5034, 2 ]
./partial_match/1/0x23a0e57620c875Cb3F1EdDcb7f8FAfBF2A466D83/sources/TWOBASED.sol
no fees for distributorsno fees between exchangerssellingbuying or selling
function _transfer(address sender, address recipient, uint256 amount) internal override { uint256 sellFeeAmount = 0; uint256 transferAmount = amount; if(!_isDistributor[sender] && !_isDistributor[recipient]) { if(!(_isExchanger[sender] && _isExchanger[recipient])) { if(_limitExpiresTimestamp >= now) { require(amount <= _limitTransferAmount, "Initial Uniswap listing - amount exceeds transfer limit"); require(balanceOf(recipient).add(amount) <= _limitMaxBalance, "Initial Uniswap listing - max balance limit"); } if(!_isExchanger[sender] && _isExchanger[recipient]) { if(_limitExpiresTimestamp >= now) { sellFeeAmount = amount.mul(_limitSellFeePercent).div(10000); sellFeeAmount = amount.mul(_sellFeePercent).div(10000); } require(_limitExpiresTimestamp < now, "Initial Uniswap listing - Wallet to Wallet transfers temporarily disabled"); } if((_isExchanger[sender] && !_isExchanger[recipient]) || (!_isExchanger[sender] && _isExchanger[recipient])) { uint256 rebasingPriceUSD = _internalRebasingPriceUSD(); if(now > _rebaseNextTimestamp && rebasingPriceUSD < _rebasePositivePriceUSD) { _rebaseJackpotLevel = 0; (uint256 priceUSD,) = getPrices(); if(priceUSD >= _rebasePositivePriceUSD) { _rebaseNextTimestamp = now + _rebaseNextSeconds; _rebaseLastPriceUSD = _rebasePositivePriceUSD; _resetRebasingPrice(); } } } } } if(sellFeeAmount > 0) { transferAmount = amount.sub(sellFeeAmount); _gonBalances[_sellFeeAddress] = _gonBalances[_sellFeeAddress].add(sellFeeAmount.mul(_gonsPerFragment)); emit Transfer(sender, _sellFeeAddress, sellFeeAmount); } uint256 gonValue = transferAmount.mul(_gonsPerFragment); _gonBalances[sender] = _gonBalances[sender].sub(gonValue); _gonBalances[recipient] = _gonBalances[recipient].add(gonValue); emit Transfer(sender, recipient, transferAmount); }
3,927,381
[ 1, 2135, 1656, 281, 364, 1015, 665, 13595, 2135, 1656, 281, 3086, 431, 24083, 414, 87, 1165, 310, 70, 9835, 310, 578, 357, 2456, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 13866, 12, 2867, 5793, 16, 1758, 8027, 16, 2254, 5034, 3844, 13, 203, 3639, 2713, 203, 3639, 3849, 203, 565, 288, 203, 3639, 2254, 5034, 357, 80, 14667, 6275, 273, 374, 31, 203, 3639, 2254, 5034, 7412, 6275, 273, 3844, 31, 203, 540, 203, 3639, 309, 12, 5, 67, 291, 1669, 19293, 63, 15330, 65, 597, 401, 67, 291, 1669, 19293, 63, 20367, 5717, 288, 203, 540, 203, 5411, 309, 12, 5, 24899, 291, 424, 343, 11455, 63, 15330, 65, 597, 389, 291, 424, 343, 11455, 63, 20367, 22643, 288, 203, 1171, 203, 7734, 309, 24899, 3595, 14449, 4921, 1545, 2037, 13, 288, 203, 10792, 2583, 12, 8949, 1648, 389, 3595, 5912, 6275, 16, 315, 4435, 1351, 291, 91, 438, 11591, 300, 3844, 14399, 7412, 1800, 8863, 203, 10792, 2583, 12, 12296, 951, 12, 20367, 2934, 1289, 12, 8949, 13, 1648, 389, 3595, 2747, 13937, 16, 315, 4435, 1351, 291, 91, 438, 11591, 300, 943, 11013, 1800, 8863, 203, 7734, 289, 203, 1171, 203, 7734, 309, 12, 5, 67, 291, 424, 343, 11455, 63, 15330, 65, 597, 389, 291, 424, 343, 11455, 63, 20367, 5717, 288, 203, 377, 203, 10792, 309, 24899, 3595, 14449, 4921, 1545, 2037, 13, 288, 203, 13491, 357, 80, 14667, 6275, 273, 3844, 18, 16411, 24899, 3595, 55, 1165, 14667, 8410, 2934, 2892, 12, 23899, 1769, 203, 13491, 357, 80, 14667, 6275, 273, 3844, 18, 16411, 24899, 87, 1165, 14667, 8410, 2934, 2892, 12, 23899, 1769, 203, 10792, 289, 203, 10792, 2583, 24899, 3595, 14449, 4921, 411, 2 ]
pragma solidity ^0.4.18; 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; } } 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); function resetTimer(string _kingdomKey); } contract PullPayment { using SafeMath for uint256; mapping(address => uint256) public payments; uint256 public totalPayments; function withdrawPayments() public { address payee = msg.sender; uint256 payment = payments[payee]; require(payment != 0); require(this.balance >= payment); totalPayments = totalPayments.sub(payment); payments[payee] = 0; assert(payee.send(payment)); } function asyncSend(address dest, uint256 amount) internal { payments[dest] = payments[dest].add(amount); totalPayments = totalPayments.add(amount); } } contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); function Ownable() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract Destructible is Ownable { function Destructible() public payable { } function destroy() onlyOwner public { selfdestruct(owner); } function destroyAndSend(address _recipient) onlyOwner public { selfdestruct(_recipient); } } contract ReentrancyGuard { bool private reentrancy_lock = false; modifier nonReentrant() { require(!reentrancy_lock); reentrancy_lock = true; _; reentrancy_lock = false; } } contract Map is PullPayment, Destructible, ReentrancyGuard { using SafeMath for uint256; // STRUCTS struct Transaction { string kingdomKey; address compensationAddress; uint buyingPrice; uint compensation; uint jackpotContribution; uint date; } struct Kingdom { string title; string key; uint kingdomTier; uint kingdomType; uint minimumPrice; uint lastTransaction; uint transactionCount; uint returnPrice; address owner; bool locked; } struct Jackpot { address winner; uint balance; } // struct RoundPoints { // mapping(address => uint) points; // } struct Round { Jackpot jackpot1; Jackpot jackpot2; Jackpot jackpot3; Jackpot jackpot4; Jackpot jackpot5; mapping(string => bool) kingdomsCreated; mapping(address => uint) nbKingdoms; mapping(address => uint) nbTransactions; mapping(address => uint) nbKingdomsType1; mapping(address => uint) nbKingdomsType2; mapping(address => uint) nbKingdomsType3; mapping(address => uint) nbKingdomsType4; mapping(address => uint) nbKingdomsType5; uint startTime; uint endTime; mapping(string => uint) kingdomsKeys; mapping(address => uint) scores; } Kingdom[] public kingdoms; Transaction[] public kingdomTransactions; uint public currentRound; address public bookerAddress; mapping(uint => Round) rounds; mapping(address => uint) lastTransaction; uint constant public ACTION_TAX = 0.02 ether; uint constant public STARTING_CLAIM_PRICE_WEI = 0.03 ether; uint constant MAXIMUM_CLAIM_PRICE_WEI = 800 ether; uint constant KINGDOM_MULTIPLIER = 20; uint constant TEAM_COMMISSION_RATIO = 10; uint constant JACKPOT_COMMISSION_RATIO = 10; // MODIFIERS modifier checkKingdomCap(address _owner, uint _kingdomType) { if (_kingdomType == 1) { require((rounds[currentRound].nbKingdomsType1[_owner] + 1) < 9); } else if (_kingdomType == 2) { require((rounds[currentRound].nbKingdomsType2[_owner] + 1) < 9); } else if (_kingdomType == 3) { require((rounds[currentRound].nbKingdomsType3[_owner] + 1) < 9); } else if (_kingdomType == 4) { require((rounds[currentRound].nbKingdomsType4[_owner] + 1) < 9); } else if (_kingdomType == 5) { require((rounds[currentRound].nbKingdomsType5[_owner] + 1) < 9); } _; } modifier onlyForRemainingKingdoms() { uint remainingKingdoms = getRemainingKingdoms(); require(remainingKingdoms > kingdoms.length); _; } modifier checkKingdomExistence(string key) { require(rounds[currentRound].kingdomsCreated[key] == true); _; } modifier checkIsNotLocked(string kingdomKey) { require(kingdoms[rounds[currentRound].kingdomsKeys[kingdomKey]].locked != true); _; } modifier checkIsClosed() { require(now >= rounds[currentRound].endTime); _; } modifier onlyKingdomOwner(string _key, address _sender) { require (kingdoms[rounds[currentRound].kingdomsKeys[_key]].owner == _sender); _; } // ERC20 address public woodAddress; ERC20Basic woodInterface; // ERC20Basic rock; // ERC20Basic // EVENTS event LandCreatedEvent(string kingdomKey, address monarchAddress); event LandPurchasedEvent(string kingdomKey, address monarchAddress); // // CONTRACT CONSTRUCTOR // function Map(address _bookerAddress, address _woodAddress, uint _startTime, uint _endTime) { bookerAddress = _bookerAddress; woodAddress = _woodAddress; woodInterface = ERC20Basic(_woodAddress); currentRound = 1; rounds[currentRound] = Round(Jackpot(address(0), 0), Jackpot(address(0), 0), Jackpot(address(0), 0), Jackpot(address(0), 0), Jackpot(address(0), 0), 0, 0); rounds[currentRound].jackpot1 = Jackpot(address(0), 0); rounds[currentRound].jackpot2 = Jackpot(address(0), 0); rounds[currentRound].jackpot3 = Jackpot(address(0), 0); rounds[currentRound].jackpot4 = Jackpot(address(0), 0); rounds[currentRound].jackpot5 = Jackpot(address(0), 0); rounds[currentRound].startTime = _startTime; rounds[currentRound].endTime = _endTime; } function () { } function setWoodAddress (address _woodAddress) public onlyOwner { woodAddress = _woodAddress; woodInterface = ERC20Basic(_woodAddress); } function getRemainingKingdoms() public view returns (uint nb) { for (uint i = 1; i < 8; i++) { if (now < rounds[currentRound].startTime + (i * 12 hours)) { uint result = (10 * i); if (result > 100) { return 100; } else { return result; } } } } // // This is the main function. It is called to buy a kingdom // function purchaseKingdom(string _key, string _title, bool _locked) public payable nonReentrant() checkKingdomExistence(_key) checkIsNotLocked(_key) { require(now < rounds[currentRound].endTime); Round storage round = rounds[currentRound]; uint kingdomId = round.kingdomsKeys[_key]; Kingdom storage kingdom = kingdoms[kingdomId]; require((kingdom.kingdomTier + 1) < 6); uint requiredPrice = kingdom.minimumPrice; if (_locked == true) { requiredPrice = requiredPrice.add(ACTION_TAX); } require (msg.value >= requiredPrice); uint jackpotCommission = (msg.value).sub(kingdom.returnPrice); if (kingdom.returnPrice > 0) { round.nbKingdoms[kingdom.owner]--; if (kingdom.kingdomType == 1) { round.nbKingdomsType1[kingdom.owner]--; } else if (kingdom.kingdomType == 2) { round.nbKingdomsType2[kingdom.owner]--; } else if (kingdom.kingdomType == 3) { round.nbKingdomsType3[kingdom.owner]--; } else if (kingdom.kingdomType == 4) { round.nbKingdomsType4[kingdom.owner]--; } else if (kingdom.kingdomType == 5) { round.nbKingdomsType5[kingdom.owner]--; } compensateLatestMonarch(kingdom.lastTransaction, kingdom.returnPrice); } // woodInterface.resetTimer(_key); kingdom.kingdomTier++; kingdom.title = _title; if (kingdom.kingdomTier == 5) { kingdom.returnPrice = 0; kingdom.minimumPrice = 5 ether; } else if (kingdom.kingdomTier == 2) { kingdom.returnPrice = 0.1125 ether; kingdom.minimumPrice = 0.27 ether; } else if (kingdom.kingdomTier == 3) { kingdom.returnPrice = 0.3375 ether; kingdom.minimumPrice = 0.81 ether; } else if (kingdom.kingdomTier == 4) { kingdom.returnPrice = 1.0125 ether; kingdom.minimumPrice = 2.43 ether; } kingdom.owner = msg.sender; kingdom.locked = _locked; uint transactionId = kingdomTransactions.push(Transaction("", msg.sender, msg.value, 0, jackpotCommission, now)) - 1; kingdomTransactions[transactionId].kingdomKey = _key; kingdom.transactionCount++; kingdom.lastTransaction = transactionId; lastTransaction[msg.sender] = now; setNewJackpot(kingdom.kingdomType, jackpotCommission, msg.sender); LandPurchasedEvent(_key, msg.sender); } function setNewJackpot(uint kingdomType, uint jackpotSplitted, address sender) internal { rounds[currentRound].nbTransactions[sender]++; rounds[currentRound].nbKingdoms[sender]++; if (kingdomType == 1) { rounds[currentRound].nbKingdomsType1[sender]++; rounds[currentRound].jackpot1.balance = rounds[currentRound].jackpot1.balance.add(jackpotSplitted); } else if (kingdomType == 2) { rounds[currentRound].nbKingdomsType2[sender]++; rounds[currentRound].jackpot2.balance = rounds[currentRound].jackpot2.balance.add(jackpotSplitted); } else if (kingdomType == 3) { rounds[currentRound].nbKingdomsType3[sender]++; rounds[currentRound].jackpot3.balance = rounds[currentRound].jackpot3.balance.add(jackpotSplitted); } else if (kingdomType == 4) { rounds[currentRound].nbKingdomsType4[sender]++; rounds[currentRound].jackpot4.balance = rounds[currentRound].jackpot4.balance.add(jackpotSplitted); } else if (kingdomType == 5) { rounds[currentRound].nbKingdomsType5[sender]++; rounds[currentRound].jackpot5.balance = rounds[currentRound].jackpot5.balance.add(jackpotSplitted); } } function setLock(string _key, bool _locked) public payable checkKingdomExistence(_key) onlyKingdomOwner(_key, msg.sender) { if (_locked == true) { require(msg.value >= ACTION_TAX); } kingdoms[rounds[currentRound].kingdomsKeys[_key]].locked = _locked; if (msg.value > 0) { asyncSend(bookerAddress, msg.value); } } function giveKingdom(address owner, string _key, string _title, uint _type) onlyOwner() public { require(_type > 0); require(_type < 6); require(rounds[currentRound].kingdomsCreated[_key] == false); uint kingdomId = kingdoms.push(Kingdom("", "", 1, _type, 0, 0, 1, 0.02 ether, address(0), false)) - 1; kingdoms[kingdomId].title = _title; kingdoms[kingdomId].owner = owner; kingdoms[kingdomId].key = _key; kingdoms[kingdomId].minimumPrice = 0.03 ether; kingdoms[kingdomId].locked = false; rounds[currentRound].kingdomsKeys[_key] = kingdomId; rounds[currentRound].kingdomsCreated[_key] = true; uint transactionId = kingdomTransactions.push(Transaction("", msg.sender, 0.01 ether, 0, 0, now)) - 1; kingdomTransactions[transactionId].kingdomKey = _key; kingdoms[kingdomId].lastTransaction = transactionId; } // // User can call this function to generate new kingdoms (within the limits of available land) // function createKingdom(string _key, string _title, uint _type, bool _locked) checkKingdomCap(msg.sender, _type) onlyForRemainingKingdoms() public payable { require(now < rounds[currentRound].endTime); require(_type > 0); require(_type < 6); uint basePrice = STARTING_CLAIM_PRICE_WEI; uint requiredPrice = basePrice; if (_locked == true) { requiredPrice = requiredPrice.add(ACTION_TAX); } require(msg.value >= requiredPrice); Round storage round = rounds[currentRound]; require(round.kingdomsCreated[_key] == false); uint refundPrice = 0.0375 ether; // (STARTING_CLAIM_PRICE_WEI.mul(125)).div(100); uint nextMinimumPrice = 0.09 ether; // STARTING_CLAIM_PRICE_WEI.add(STARTING_CLAIM_PRICE_WEI.mul(2)); uint kingdomId = kingdoms.push(Kingdom("", "", 1, 0, 0, 0, 1, refundPrice, address(0), false)) - 1; kingdoms[kingdomId].kingdomType = _type; kingdoms[kingdomId].title = _title; kingdoms[kingdomId].owner = msg.sender; kingdoms[kingdomId].key = _key; kingdoms[kingdomId].minimumPrice = nextMinimumPrice; kingdoms[kingdomId].locked = _locked; round.kingdomsKeys[_key] = kingdomId; round.kingdomsCreated[_key] = true; if(_locked == true) { asyncSend(bookerAddress, ACTION_TAX); } uint transactionId = kingdomTransactions.push(Transaction("", msg.sender, msg.value, 0, basePrice, now)) - 1; kingdomTransactions[transactionId].kingdomKey = _key; kingdoms[kingdomId].lastTransaction = transactionId; lastTransaction[msg.sender] = now; setNewJackpot(_type, basePrice, msg.sender); LandCreatedEvent(_key, msg.sender); } // // Send transaction to compensate the previous owner // function compensateLatestMonarch(uint lastTransaction, uint compensationWei) internal { address compensationAddress = kingdomTransactions[lastTransaction].compensationAddress; kingdomTransactions[lastTransaction].compensation = compensationWei; asyncSend(compensationAddress, compensationWei); } // // This function may be useful to force withdraw if user never come back to get his money // function forceWithdrawPayments(address payee) public onlyOwner { uint256 payment = payments[payee]; require(payment != 0); require(this.balance >= payment); totalPayments = totalPayments.sub(payment); payments[payee] = 0; assert(payee.send(payment)); } function getStartTime() public view returns (uint startTime) { return rounds[currentRound].startTime; } function getEndTime() public view returns (uint endTime) { return rounds[currentRound].endTime; } function payJackpot1() internal checkIsClosed() { address winner = getWinner(1); if (rounds[currentRound].jackpot1.balance > 0 && winner != address(0)) { require(this.balance >= rounds[currentRound].jackpot1.balance); rounds[currentRound].jackpot1.winner = winner; uint teamComission = (rounds[currentRound].jackpot1.balance.mul(TEAM_COMMISSION_RATIO)).div(100); bookerAddress.transfer(teamComission); uint jackpot = rounds[currentRound].jackpot1.balance.sub(teamComission); asyncSend(winner, jackpot); rounds[currentRound].jackpot1.balance = 0; } } function payJackpot2() internal checkIsClosed() { address winner = getWinner(2); if (rounds[currentRound].jackpot2.balance > 0 && winner != address(0)) { require(this.balance >= rounds[currentRound].jackpot2.balance); rounds[currentRound].jackpot2.winner = winner; uint teamComission = (rounds[currentRound].jackpot2.balance.mul(TEAM_COMMISSION_RATIO)).div(100); bookerAddress.transfer(teamComission); uint jackpot = rounds[currentRound].jackpot2.balance.sub(teamComission); asyncSend(winner, jackpot); rounds[currentRound].jackpot2.balance = 0; } } function payJackpot3() internal checkIsClosed() { address winner = getWinner(3); if (rounds[currentRound].jackpot3.balance > 0 && winner != address(0)) { require(this.balance >= rounds[currentRound].jackpot3.balance); rounds[currentRound].jackpot3.winner = winner; uint teamComission = (rounds[currentRound].jackpot3.balance.mul(TEAM_COMMISSION_RATIO)).div(100); bookerAddress.transfer(teamComission); uint jackpot = rounds[currentRound].jackpot3.balance.sub(teamComission); asyncSend(winner, jackpot); rounds[currentRound].jackpot3.balance = 0; } } function payJackpot4() internal checkIsClosed() { address winner = getWinner(4); if (rounds[currentRound].jackpot4.balance > 0 && winner != address(0)) { require(this.balance >= rounds[currentRound].jackpot4.balance); rounds[currentRound].jackpot4.winner = winner; uint teamComission = (rounds[currentRound].jackpot4.balance.mul(TEAM_COMMISSION_RATIO)).div(100); bookerAddress.transfer(teamComission); uint jackpot = rounds[currentRound].jackpot4.balance.sub(teamComission); asyncSend(winner, jackpot); rounds[currentRound].jackpot4.balance = 0; } } function payJackpot5() internal checkIsClosed() { address winner = getWinner(5); if (rounds[currentRound].jackpot5.balance > 0 && winner != address(0)) { require(this.balance >= rounds[currentRound].jackpot5.balance); rounds[currentRound].jackpot5.winner = winner; uint teamComission = (rounds[currentRound].jackpot5.balance.mul(TEAM_COMMISSION_RATIO)).div(100); bookerAddress.transfer(teamComission); uint jackpot = rounds[currentRound].jackpot5.balance.sub(teamComission); asyncSend(winner, jackpot); rounds[currentRound].jackpot5.balance = 0; } } // // After time expiration, owner can call this function to activate the next round of the game // function activateNextRound(uint _startTime) public checkIsClosed() { payJackpot1(); payJackpot2(); payJackpot3(); payJackpot4(); payJackpot5(); currentRound++; rounds[currentRound] = Round(Jackpot(address(0), 0), Jackpot(address(0), 0), Jackpot(address(0), 0), Jackpot(address(0), 0), Jackpot(address(0), 0), 0, 0); rounds[currentRound].startTime = _startTime; rounds[currentRound].endTime = _startTime + 7 days; delete kingdoms; delete kingdomTransactions; } // GETTER AND SETTER FUNCTIONS function getKingdomCount() public view returns (uint kingdomCount) { return kingdoms.length; } function getJackpot(uint _nb) public view returns (address winner, uint balance) { if (_nb == 1) { return (getWinner(1), rounds[currentRound].jackpot1.balance); } else if (_nb == 2) { return (getWinner(2), rounds[currentRound].jackpot2.balance); } else if (_nb == 3) { return (getWinner(3), rounds[currentRound].jackpot3.balance); } else if (_nb == 4) { return (getWinner(4), rounds[currentRound].jackpot4.balance); } else if (_nb == 5) { return (getWinner(5), rounds[currentRound].jackpot5.balance); } } function getKingdomType(string _kingdomKey) public view returns (uint kingdomType) { return kingdoms[rounds[currentRound].kingdomsKeys[_kingdomKey]].kingdomType; } function getKingdomOwner(string _kingdomKey) public view returns (address owner) { return kingdoms[rounds[currentRound].kingdomsKeys[_kingdomKey]].owner; } function getKingdomInformations(string _kingdomKey) public view returns (string title, uint minimumPrice, uint lastTransaction, uint transactionCount, address currentOwner, uint kingdomType, bool locked) { uint kingdomId = rounds[currentRound].kingdomsKeys[_kingdomKey]; Kingdom storage kingdom = kingdoms[kingdomId]; return (kingdom.title, kingdom.minimumPrice, kingdom.lastTransaction, kingdom.transactionCount, kingdom.owner, kingdom.kingdomType, kingdom.locked); } // function upgradeTier(string _key) public { // // require(now < rounds[currentRound].endTime); // Round storage round = rounds[currentRound]; // uint kingdomId = round.kingdomsKeys[_key]; // Kingdom storage kingdom = kingdoms[kingdomId]; // uint wood = woodInterface.balanceOf(kingdom.owner); // require(wood >= 1); // kingdom.kingdomTier++; // } function getWinner(uint _type) public returns (address winner) { require(_type > 0); require(_type < 6); address addr; uint maxPoints = 0; Round storage round = rounds[currentRound]; for (uint index = 0; index < kingdoms.length; index++) { if (_type == kingdoms[index].kingdomType) { address userAddress = kingdoms[index].owner; if(kingdoms[index].kingdomTier == 1) { round.scores[msg.sender] = round.scores[msg.sender] + 1; } else if(kingdoms[index].kingdomTier == 2) { round.scores[msg.sender] = round.scores[msg.sender] + 3; } else if (kingdoms[index].kingdomTier == 3) { round.scores[msg.sender] = round.scores[msg.sender] + 5; } else if (kingdoms[index].kingdomTier == 4) { round.scores[msg.sender] = round.scores[msg.sender] + 8; } else if (kingdoms[index].kingdomTier == 5) { round.scores[msg.sender] = round.scores[msg.sender] + 13; } if(round.scores[msg.sender] == maxPoints) { if(lastTransaction[userAddress] < lastTransaction[winner]) { addr = userAddress; } } else if (round.scores[msg.sender] > maxPoints) { maxPoints = round.scores[msg.sender]; addr = userAddress; } } } return addr; } }
STARTING_CLAIM_PRICE_WEI.add(STARTING_CLAIM_PRICE_WEI.mul(2));
uint nextMinimumPrice = 0.09 ether;
10,692,848
[ 1, 7570, 1360, 67, 15961, 3445, 67, 7698, 1441, 67, 6950, 45, 18, 1289, 12, 7570, 1360, 67, 15961, 3445, 67, 7698, 1441, 67, 6950, 45, 18, 16411, 12, 22, 10019, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2254, 1024, 13042, 5147, 273, 374, 18, 5908, 225, 2437, 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 ]
pragma solidity ^0.5.0; // Copyright © 2017, 2018 Weald Technology Trading Limited // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import '../math/SafeMath.sol'; import './ITokenStore.sol'; /** * @title SimpleTokenStore * SimpleTokenStore provides storage for an ERC-20 contract separate from * the contract itself. This separation of token logic and storage * allows upgrades to token functionality without requiring expensive * copying of the token allocation information. * * Calling functions that alter the token distribution require the caller * to have the PERM_ACT permission. * * Note that this contract is aggressively ERC-20 non-compliant, to avoid * any confusion that this might be a token contract in its own right. * * Also note that this contract does not emit any events; that is the job * of the token contract. * * This contract has individual permissions for each major operation. * These are: * - PERM_MINT: permission to mint new tokens * - PERM_BURN: permission to burn existing tokens * - PERM_TRANSFER: permission to transfer tokens from own holder to * another regardless of allowance * - PERM_SET_ALLOWANCE: permission to set the number of tokens allowed * to be transferred from one holder to another * - PERM_USE_ALLOWANCE: permission to transfer tokens from one holder * to another within the bounds of the allowance * * State of this contract: stable; development complete but the code is * unaudited. and may contain bugs and/or security holes. Use at your own * risk. * * @author Jim McDonald * @notice If you use this contract please consider donating some Ether or * some of your ERC-20 token to wsl.wealdtech.eth to support continued * development of these and future contracts */ contract SimpleTokenStore is ITokenStore { using SafeMath for uint256; // Keep track of balances and allowances mapping(address=>uint256) internal balances; mapping(address=>mapping(address=>uint256)) internal allowances; // Flag to enable/disable minting bool public mintingEnabled; // Permissions for each operation bytes32 internal constant PERM_MINT = keccak256("token storage: mint"); bytes32 internal constant PERM_BURN = keccak256("token storage: burn"); bytes32 internal constant PERM_DISBALE_MINTING = keccak256("token storage: disable minting"); bytes32 internal constant PERM_TRANSFER = keccak256("token storage: transfer"); bytes32 internal constant PERM_SET_ALLOWANCE = keccak256("token storage: set allowance"); bytes32 internal constant PERM_USE_ALLOWANCE = keccak256("token storage: use allowance"); /** * @dev Constructor * This is usually called by a token contract. */ constructor() public { mintingEnabled = true; } /** * @dev Fallback. * This contract does not accept funds, so revert */ function () external { revert(); } /** * @dev Permanently disable minting of tokens. */ function disableMinting() public ifPermitted(msg.sender, PERM_DISBALE_MINTING) { mintingEnabled = false; } /** * @dev Mint tokens and allocate them to a recipient. */ function mint(address _recipient, uint256 _amount) public ifPermitted(msg.sender, PERM_MINT) { require(mintingEnabled, "minting disabled"); balances[_recipient] = balances[_recipient].add(_amount); totalSupply = totalSupply.add(_amount); } /** * @dev Burn tokens and remove them from the total supply */ function burn(address _holder, uint256 _amount) public ifPermitted(msg.sender, PERM_BURN) { balances[_holder] = balances[_holder].sub(_amount); totalSupply = totalSupply.sub(_amount); } /** * @dev Transfer tokens directly from owner to recipient, bypassing * allowances. */ function transfer(address _owner, address _recipient, uint256 _amount) public ifPermitted(msg.sender, PERM_TRANSFER) { balances[_owner] = balances[_owner].sub(_amount); balances[_recipient] = balances[_recipient].add(_amount); } /** * @dev Obtain a balance. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } /** * @dev Set an allowance for a (sender, recipient) pair * The amount of funds must not be more than the sender's current * balance. * Note that it is not permitted to change an allocation from a * non-zero number to another non-zero number, due to potential race * conditions with transactions. Allocations must always go from * zero to non-zero, or non-zero to zero. */ function setAllowance(address _owner, address _recipient, uint256 _amount) public ifPermitted(msg.sender, PERM_SET_ALLOWANCE) { require((_amount == 0) || (allowances[_owner][_recipient] == 0)); allowances[_owner][_recipient] = _amount; } /** * @dev Use up some or all of an allocation of tokens. * Note that this allows third-party transfer of tokens, such that * if A gives B an allowance of 10 tokens it is possible for B to * transfer those 10 tokens directly from A to C. */ function useAllowance(address _owner, address _allowanceHolder, address _recipient, uint256 _amount) public ifPermitted(msg.sender, PERM_USE_ALLOWANCE) { uint256 allowance = allowances[_owner][_allowanceHolder]; balances[_owner] = balances[_owner].sub(_amount); balances[_recipient] = balances[_recipient].add(_amount); allowances[_owner][_allowanceHolder] = allowance.sub(_amount); } /** * @dev Obtain an allowance. * Note that it is possible for the allowance to be higher than the * owner's balance, so if using this information to consider if an * address can pay a certain amount it is important to check using * both the values obtain from this and balanceOf(). */ function allowanceOf(address _owner, address _recipient) public view returns (uint256) { return allowances[_owner][_recipient]; } // Nothing to sync function sync(address) public {} }
* @title SimpleTokenStore SimpleTokenStore provides storage for an ERC-20 contract separate from the contract itself. This separation of token logic and storage allows upgrades to token functionality without requiring expensive copying of the token allocation information. Calling functions that alter the token distribution require the caller to have the PERM_ACT permission. Note that this contract is aggressively ERC-20 non-compliant, to avoid any confusion that this might be a token contract in its own right. Also note that this contract does not emit any events; that is the job of the token contract. This contract has individual permissions for each major operation. These are: - PERM_MINT: permission to mint new tokens - PERM_BURN: permission to burn existing tokens - PERM_TRANSFER: permission to transfer tokens from own holder to another regardless of allowance - PERM_SET_ALLOWANCE: permission to set the number of tokens allowed to be transferred from one holder to another - PERM_USE_ALLOWANCE: permission to transfer tokens from one holder to another within the bounds of the allowance State of this contract: stable; development complete but the code is unaudited. and may contain bugs and/or security holes. Use at your own risk. @author Jim McDonald @notice If you use this contract please consider donating some Ether or some of your ERC-20 token to wsl.wealdtech.eth to support continued development of these and future contracts/ Keep track of balances and allowances Flag to enable/disable minting Permissions for each operation
contract SimpleTokenStore is ITokenStore { using SafeMath for uint256; mapping(address=>uint256) internal balances; mapping(address=>mapping(address=>uint256)) internal allowances; bool public mintingEnabled; bytes32 internal constant PERM_MINT = keccak256("token storage: mint"); bytes32 internal constant PERM_BURN = keccak256("token storage: burn"); bytes32 internal constant PERM_DISBALE_MINTING = keccak256("token storage: disable minting"); bytes32 internal constant PERM_TRANSFER = keccak256("token storage: transfer"); bytes32 internal constant PERM_SET_ALLOWANCE = keccak256("token storage: set allowance"); bytes32 internal constant PERM_USE_ALLOWANCE = keccak256("token storage: use allowance"); constructor() public { mintingEnabled = true; } function () external { revert(); } function disableMinting() public ifPermitted(msg.sender, PERM_DISBALE_MINTING) { mintingEnabled = false; } function mint(address _recipient, uint256 _amount) public ifPermitted(msg.sender, PERM_MINT) { require(mintingEnabled, "minting disabled"); balances[_recipient] = balances[_recipient].add(_amount); totalSupply = totalSupply.add(_amount); } function burn(address _holder, uint256 _amount) public ifPermitted(msg.sender, PERM_BURN) { balances[_holder] = balances[_holder].sub(_amount); totalSupply = totalSupply.sub(_amount); } function transfer(address _owner, address _recipient, uint256 _amount) public ifPermitted(msg.sender, PERM_TRANSFER) { balances[_owner] = balances[_owner].sub(_amount); balances[_recipient] = balances[_recipient].add(_amount); } function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } function setAllowance(address _owner, address _recipient, uint256 _amount) public ifPermitted(msg.sender, PERM_SET_ALLOWANCE) { require((_amount == 0) || (allowances[_owner][_recipient] == 0)); allowances[_owner][_recipient] = _amount; } function useAllowance(address _owner, address _allowanceHolder, address _recipient, uint256 _amount) public ifPermitted(msg.sender, PERM_USE_ALLOWANCE) { uint256 allowance = allowances[_owner][_allowanceHolder]; balances[_owner] = balances[_owner].sub(_amount); balances[_recipient] = balances[_recipient].add(_amount); allowances[_owner][_allowanceHolder] = allowance.sub(_amount); } function allowanceOf(address _owner, address _recipient) public view returns (uint256) { return allowances[_owner][_recipient]; } function sync(address) public {} }
1,060,016
[ 1, 5784, 1345, 2257, 3639, 4477, 1345, 2257, 8121, 2502, 364, 392, 4232, 39, 17, 3462, 6835, 9004, 628, 3639, 326, 6835, 6174, 18, 225, 1220, 5102, 367, 434, 1147, 4058, 471, 2502, 3639, 5360, 28844, 358, 1147, 14176, 2887, 29468, 19326, 3639, 8933, 434, 326, 1147, 13481, 1779, 18, 3639, 21020, 4186, 716, 10182, 326, 1147, 7006, 2583, 326, 4894, 3639, 358, 1240, 326, 10950, 49, 67, 6526, 4132, 18, 3639, 3609, 716, 333, 6835, 353, 1737, 2329, 4492, 4232, 39, 17, 3462, 1661, 17, 832, 18515, 16, 358, 4543, 3639, 1281, 31067, 716, 333, 4825, 506, 279, 1147, 6835, 316, 2097, 4953, 2145, 18, 3639, 8080, 4721, 716, 333, 6835, 1552, 486, 3626, 1281, 2641, 31, 716, 353, 326, 1719, 3639, 434, 326, 1147, 6835, 18, 3639, 1220, 6835, 711, 7327, 4371, 364, 1517, 7888, 1674, 18, 3639, 8646, 854, 30, 1850, 300, 10950, 49, 67, 49, 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, 4477, 1345, 2257, 353, 467, 1345, 2257, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 565, 2874, 12, 2867, 9207, 11890, 5034, 13, 2713, 324, 26488, 31, 203, 565, 2874, 12, 2867, 9207, 6770, 12, 2867, 9207, 11890, 5034, 3719, 2713, 1699, 6872, 31, 203, 203, 565, 1426, 1071, 312, 474, 310, 1526, 31, 203, 203, 565, 1731, 1578, 2713, 5381, 10950, 49, 67, 49, 3217, 273, 417, 24410, 581, 5034, 2932, 2316, 2502, 30, 312, 474, 8863, 203, 565, 1731, 1578, 2713, 5381, 10950, 49, 67, 38, 8521, 273, 417, 24410, 581, 5034, 2932, 2316, 2502, 30, 18305, 8863, 203, 565, 1731, 1578, 2713, 5381, 10950, 49, 67, 13498, 12536, 900, 67, 49, 3217, 1360, 273, 417, 24410, 581, 5034, 2932, 2316, 2502, 30, 4056, 312, 474, 310, 8863, 203, 565, 1731, 1578, 2713, 5381, 10950, 49, 67, 16596, 6553, 273, 417, 24410, 581, 5034, 2932, 2316, 2502, 30, 7412, 8863, 203, 565, 1731, 1578, 2713, 5381, 10950, 49, 67, 4043, 67, 13511, 4722, 273, 417, 24410, 581, 5034, 2932, 2316, 2502, 30, 444, 1699, 1359, 8863, 203, 565, 1731, 1578, 2713, 5381, 10950, 49, 67, 8001, 67, 13511, 4722, 273, 417, 24410, 581, 5034, 2932, 2316, 2502, 30, 999, 1699, 1359, 8863, 203, 203, 203, 565, 3885, 1435, 1071, 288, 203, 3639, 312, 474, 310, 1526, 273, 638, 31, 203, 565, 289, 203, 203, 565, 445, 1832, 3903, 288, 203, 3639, 15226, 5621, 203, 565, 289, 203, 203, 565, 445, 4056, 49, 474, 310, 1435, 1071, 309, 2 ]
./full_match/4/0x507CdaD90F8AE7D4BBa5e05F2a1012f7f4b07053/sources/_aave/core-v3/contracts/misc/AaveProtocolDataProvider.sol
* @notice Returns the debt ceiling decimals @return The debt ceiling decimals/
function getDebtCeilingDecimals() external pure returns (uint256) { return ReserveConfiguration.DEBT_CEILING_DECIMALS; }
661,612
[ 1, 1356, 326, 18202, 88, 5898, 4973, 15105, 327, 1021, 18202, 88, 5898, 4973, 15105, 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, 225, 445, 336, 758, 23602, 39, 73, 4973, 31809, 1435, 3903, 16618, 1135, 261, 11890, 5034, 13, 288, 203, 565, 327, 1124, 6527, 1750, 18, 1639, 38, 56, 67, 1441, 2627, 1360, 67, 23816, 55, 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 ]