|
{
|
|
"language": "Solidity",
|
|
"sources": {
|
|
"contracts/governance/Timelock.sol": {
|
|
"content": "// SPDX-License-Identifier: MIT\n\n// COPIED FROM https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/GovernorAlpha.sol\n// Copyright 2020 Compound Labs, Inc.\n// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\n// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\n// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.\n// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n//\n// Ctrl+f for XXX to see all the modifications.\n\n// XXX: pragma solidity ^0.5.16;\npragma solidity 0.6.12;\n\n// XXX: import \"./SafeMath.sol\";\nimport \"@openzeppelin/contracts/math/SafeMath.sol\";\n\ncontract Timelock {\n using SafeMath for uint;\n\n event NewAdmin(address indexed newAdmin);\n event NewPendingAdmin(address indexed newPendingAdmin);\n event NewDelay(uint indexed newDelay);\n event CancelTransaction(bytes32 indexed txHash, address indexed target, uint value, string signature, bytes data, uint eta);\n event ExecuteTransaction(bytes32 indexed txHash, address indexed target, uint value, string signature, bytes data, uint eta);\n event QueueTransaction(bytes32 indexed txHash, address indexed target, uint value, string signature, bytes data, uint eta);\n\n uint public constant GRACE_PERIOD = 14 days;\n uint public constant MINIMUM_DELAY = 2 days;\n uint public constant MAXIMUM_DELAY = 30 days;\n\n address public admin;\n address public pendingAdmin;\n uint public delay;\n bool public admin_initialized;\n\n mapping (bytes32 => bool) public queuedTransactions;\n\n\n constructor(address admin_, uint delay_) public {\n require(delay_ >= MINIMUM_DELAY, \"Timelock::constructor: Delay must exceed minimum delay.\");\n require(delay_ <= MAXIMUM_DELAY, \"Timelock::constructor: Delay must not exceed maximum delay.\");\n\n admin = admin_;\n delay = delay_;\n admin_initialized = false;\n }\n\n // XXX: function() external payable { }\n receive() external payable { }\n\n function setDelay(uint delay_) public {\n require(msg.sender == address(this), \"Timelock::setDelay: Call must come from Timelock.\");\n require(delay_ >= MINIMUM_DELAY, \"Timelock::setDelay: Delay must exceed minimum delay.\");\n require(delay_ <= MAXIMUM_DELAY, \"Timelock::setDelay: Delay must not exceed maximum delay.\");\n delay = delay_;\n\n emit NewDelay(delay);\n }\n\n function acceptAdmin() public {\n require(msg.sender == pendingAdmin, \"Timelock::acceptAdmin: Call must come from pendingAdmin.\");\n admin = msg.sender;\n pendingAdmin = address(0);\n\n emit NewAdmin(admin);\n }\n\n function setPendingAdmin(address pendingAdmin_) public {\n // allows one time setting of admin for deployment purposes\n if (admin_initialized) {\n require(msg.sender == address(this), \"Timelock::setPendingAdmin: Call must come from Timelock.\");\n } else {\n require(msg.sender == admin, \"Timelock::setPendingAdmin: First call must come from admin.\");\n admin_initialized = true;\n }\n pendingAdmin = pendingAdmin_;\n\n emit NewPendingAdmin(pendingAdmin);\n }\n\n function queueTransaction(address target, uint value, string memory signature, bytes memory data, uint eta) public returns (bytes32) {\n require(msg.sender == admin, \"Timelock::queueTransaction: Call must come from admin.\");\n require(eta >= getBlockTimestamp().add(delay), \"Timelock::queueTransaction: Estimated execution block must satisfy delay.\");\n\n bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta));\n queuedTransactions[txHash] = true;\n\n emit QueueTransaction(txHash, target, value, signature, data, eta);\n return txHash;\n }\n\n function cancelTransaction(address target, uint value, string memory signature, bytes memory data, uint eta) public {\n require(msg.sender == admin, \"Timelock::cancelTransaction: Call must come from admin.\");\n\n bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta));\n queuedTransactions[txHash] = false;\n\n emit CancelTransaction(txHash, target, value, signature, data, eta);\n }\n\n function executeTransaction(address target, uint value, string memory signature, bytes memory data, uint eta) public payable returns (bytes memory) {\n require(msg.sender == admin, \"Timelock::executeTransaction: Call must come from admin.\");\n\n bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta));\n require(queuedTransactions[txHash], \"Timelock::executeTransaction: Transaction hasn't been queued.\");\n require(getBlockTimestamp() >= eta, \"Timelock::executeTransaction: Transaction hasn't surpassed time lock.\");\n require(getBlockTimestamp() <= eta.add(GRACE_PERIOD), \"Timelock::executeTransaction: Transaction is stale.\");\n\n queuedTransactions[txHash] = false;\n\n bytes memory callData;\n\n if (bytes(signature).length == 0) {\n callData = data;\n } else {\n callData = abi.encodePacked(bytes4(keccak256(bytes(signature))), data);\n }\n\n // solium-disable-next-line security/no-call-value\n (bool success, bytes memory returnData) = target.call.value(value)(callData);\n require(success, \"Timelock::executeTransaction: Transaction execution reverted.\");\n\n emit ExecuteTransaction(txHash, target, value, signature, data, eta);\n\n return returnData;\n }\n\n function getBlockTimestamp() internal view returns (uint) {\n // solium-disable-next-line security/no-block-members\n return block.timestamp;\n }\n}"
|
|
},
|
|
"@openzeppelin/contracts/math/SafeMath.sol": {
|
|
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.6.0 <0.8.0;\n\n/**\n * @dev Wrappers over Solidity's arithmetic operations with added overflow\n * checks.\n *\n * Arithmetic operations in Solidity wrap on overflow. This can easily result\n * in bugs, because programmers usually assume that an overflow raises an\n * error, which is the standard behavior in high level programming languages.\n * `SafeMath` restores this intuition by reverting the transaction when an\n * operation overflows.\n *\n * Using this library instead of the unchecked operations eliminates an entire\n * class of bugs, so it's recommended to use it always.\n */\nlibrary SafeMath {\n /**\n * @dev Returns the addition of two unsigned integers, with an overflow flag.\n *\n * _Available since v3.4._\n */\n function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n uint256 c = a + b;\n if (c < a) return (false, 0);\n return (true, c);\n }\n\n /**\n * @dev Returns the substraction of two unsigned integers, with an overflow flag.\n *\n * _Available since v3.4._\n */\n function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n if (b > a) return (false, 0);\n return (true, a - b);\n }\n\n /**\n * @dev Returns the multiplication of two unsigned integers, with an overflow flag.\n *\n * _Available since v3.4._\n */\n function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n // Gas optimization: this is cheaper than requiring 'a' not being zero, but the\n // benefit is lost if 'b' is also tested.\n // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522\n if (a == 0) return (true, 0);\n uint256 c = a * b;\n if (c / a != b) return (false, 0);\n return (true, c);\n }\n\n /**\n * @dev Returns the division of two unsigned integers, with a division by zero flag.\n *\n * _Available since v3.4._\n */\n function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n if (b == 0) return (false, 0);\n return (true, a / b);\n }\n\n /**\n * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.\n *\n * _Available since v3.4._\n */\n function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n if (b == 0) return (false, 0);\n return (true, a % b);\n }\n\n /**\n * @dev Returns the addition of two unsigned integers, reverting on\n * overflow.\n *\n * Counterpart to Solidity's `+` operator.\n *\n * Requirements:\n *\n * - Addition cannot overflow.\n */\n function add(uint256 a, uint256 b) internal pure returns (uint256) {\n uint256 c = a + b;\n require(c >= a, \"SafeMath: addition overflow\");\n return c;\n }\n\n /**\n * @dev Returns the subtraction of two unsigned integers, reverting on\n * overflow (when the result is negative).\n *\n * Counterpart to Solidity's `-` operator.\n *\n * Requirements:\n *\n * - Subtraction cannot overflow.\n */\n function sub(uint256 a, uint256 b) internal pure returns (uint256) {\n require(b <= a, \"SafeMath: subtraction overflow\");\n return a - b;\n }\n\n /**\n * @dev Returns the multiplication of two unsigned integers, reverting on\n * overflow.\n *\n * Counterpart to Solidity's `*` operator.\n *\n * Requirements:\n *\n * - Multiplication cannot overflow.\n */\n function mul(uint256 a, uint256 b) internal pure returns (uint256) {\n if (a == 0) return 0;\n uint256 c = a * b;\n require(c / a == b, \"SafeMath: multiplication overflow\");\n return c;\n }\n\n /**\n * @dev Returns the integer division of two unsigned integers, reverting on\n * division by zero. The result is rounded towards zero.\n *\n * Counterpart to Solidity's `/` operator. Note: this function uses a\n * `revert` opcode (which leaves remaining gas untouched) while Solidity\n * uses an invalid opcode to revert (consuming all remaining gas).\n *\n * Requirements:\n *\n * - The divisor cannot be zero.\n */\n function div(uint256 a, uint256 b) internal pure returns (uint256) {\n require(b > 0, \"SafeMath: division by zero\");\n return a / b;\n }\n\n /**\n * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),\n * reverting when dividing by zero.\n *\n * Counterpart to Solidity's `%` operator. This function uses a `revert`\n * opcode (which leaves remaining gas untouched) while Solidity uses an\n * invalid opcode to revert (consuming all remaining gas).\n *\n * Requirements:\n *\n * - The divisor cannot be zero.\n */\n function mod(uint256 a, uint256 b) internal pure returns (uint256) {\n require(b > 0, \"SafeMath: modulo by zero\");\n return a % b;\n }\n\n /**\n * @dev Returns the subtraction of two unsigned integers, reverting with custom message on\n * overflow (when the result is negative).\n *\n * CAUTION: This function is deprecated because it requires allocating memory for the error\n * message unnecessarily. For custom revert reasons use {trySub}.\n *\n * Counterpart to Solidity's `-` operator.\n *\n * Requirements:\n *\n * - Subtraction cannot overflow.\n */\n function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {\n require(b <= a, errorMessage);\n return a - b;\n }\n\n /**\n * @dev Returns the integer division of two unsigned integers, reverting with custom message on\n * division by zero. The result is rounded towards zero.\n *\n * CAUTION: This function is deprecated because it requires allocating memory for the error\n * message unnecessarily. For custom revert reasons use {tryDiv}.\n *\n * Counterpart to Solidity's `/` operator. Note: this function uses a\n * `revert` opcode (which leaves remaining gas untouched) while Solidity\n * uses an invalid opcode to revert (consuming all remaining gas).\n *\n * Requirements:\n *\n * - The divisor cannot be zero.\n */\n function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {\n require(b > 0, errorMessage);\n return a / b;\n }\n\n /**\n * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),\n * reverting with custom message when dividing by zero.\n *\n * CAUTION: This function is deprecated because it requires allocating memory for the error\n * message unnecessarily. For custom revert reasons use {tryMod}.\n *\n * Counterpart to Solidity's `%` operator. This function uses a `revert`\n * opcode (which leaves remaining gas untouched) while Solidity uses an\n * invalid opcode to revert (consuming all remaining gas).\n *\n * Requirements:\n *\n * - The divisor cannot be zero.\n */\n function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {\n require(b > 0, errorMessage);\n return a % b;\n }\n}\n"
|
|
},
|
|
"contracts/SushiBar.sol": {
|
|
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity 0.6.12;\n\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/ERC20.sol\";\nimport \"@openzeppelin/contracts/math/SafeMath.sol\";\n\n// SushiBar is the coolest bar in town. You come in with some Sushi, and leave with more! The longer you stay, the more Sushi you get.\n//\n// This contract handles swapping to and from xSushi, SushiSwap's staking token.\ncontract SushiBar is ERC20(\"SushiBar\", \"xSUSHI\"){\n using SafeMath for uint256;\n IERC20 public sushi;\n\n // Define the Sushi token contract\n constructor(IERC20 _sushi) public {\n sushi = _sushi;\n }\n\n // Enter the bar. Pay some SUSHIs. Earn some shares.\n // Locks Sushi and mints xSushi\n function enter(uint256 _amount) public {\n // Gets the amount of Sushi locked in the contract\n uint256 totalSushi = sushi.balanceOf(address(this));\n // Gets the amount of xSushi in existence\n uint256 totalShares = totalSupply();\n // If no xSushi exists, mint it 1:1 to the amount put in\n if (totalShares == 0 || totalSushi == 0) {\n _mint(msg.sender, _amount);\n } \n // Calculate and mint the amount of xSushi the Sushi is worth. The ratio will change overtime, as xSushi is burned/minted and Sushi deposited + gained from fees / withdrawn.\n else {\n uint256 what = _amount.mul(totalShares).div(totalSushi);\n _mint(msg.sender, what);\n }\n // Lock the Sushi in the contract\n sushi.transferFrom(msg.sender, address(this), _amount);\n }\n\n // Leave the bar. Claim back your SUSHIs.\n // Unlocks the staked + gained Sushi and burns xSushi\n function leave(uint256 _share) public {\n // Gets the amount of xSushi in existence\n uint256 totalShares = totalSupply();\n // Calculates the amount of Sushi the xSushi is worth\n uint256 what = _share.mul(sushi.balanceOf(address(this))).div(totalShares);\n _burn(msg.sender, _share);\n sushi.transfer(msg.sender, what);\n }\n}\n"
|
|
},
|
|
"@openzeppelin/contracts/token/ERC20/IERC20.sol": {
|
|
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.6.0 <0.8.0;\n\n/**\n * @dev Interface of the ERC20 standard as defined in the EIP.\n */\ninterface IERC20 {\n /**\n * @dev Returns the amount of tokens in existence.\n */\n function totalSupply() external view returns (uint256);\n\n /**\n * @dev Returns the amount of tokens owned by `account`.\n */\n function balanceOf(address account) external view returns (uint256);\n\n /**\n * @dev Moves `amount` tokens from the caller's account to `recipient`.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transfer(address recipient, uint256 amount) external returns (bool);\n\n /**\n * @dev Returns the remaining number of tokens that `spender` will be\n * allowed to spend on behalf of `owner` through {transferFrom}. This is\n * zero by default.\n *\n * This value changes when {approve} or {transferFrom} are called.\n */\n function allowance(address owner, address spender) external view returns (uint256);\n\n /**\n * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * IMPORTANT: Beware that changing an allowance with this method brings the risk\n * that someone may use both the old and the new allowance by unfortunate\n * transaction ordering. One possible solution to mitigate this race\n * condition is to first reduce the spender's allowance to 0 and set the\n * desired value afterwards:\n * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\n *\n * Emits an {Approval} event.\n */\n function approve(address spender, uint256 amount) external returns (bool);\n\n /**\n * @dev Moves `amount` tokens from `sender` to `recipient` using the\n * allowance mechanism. `amount` is then deducted from the caller's\n * allowance.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);\n\n /**\n * @dev Emitted when `value` tokens are moved from one account (`from`) to\n * another (`to`).\n *\n * Note that `value` may be zero.\n */\n event Transfer(address indexed from, address indexed to, uint256 value);\n\n /**\n * @dev Emitted when the allowance of a `spender` for an `owner` is set by\n * a call to {approve}. `value` is the new allowance.\n */\n event Approval(address indexed owner, address indexed spender, uint256 value);\n}\n"
|
|
},
|
|
"@openzeppelin/contracts/token/ERC20/ERC20.sol": {
|
|
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.6.0 <0.8.0;\n\nimport \"../../utils/Context.sol\";\nimport \"./IERC20.sol\";\nimport \"../../math/SafeMath.sol\";\n\n/**\n * @dev Implementation of the {IERC20} interface.\n *\n * This implementation is agnostic to the way tokens are created. This means\n * that a supply mechanism has to be added in a derived contract using {_mint}.\n * For a generic mechanism see {ERC20PresetMinterPauser}.\n *\n * TIP: For a detailed writeup see our guide\n * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How\n * to implement supply mechanisms].\n *\n * We have followed general OpenZeppelin guidelines: functions revert instead\n * of returning `false` on failure. This behavior is nonetheless conventional\n * and does not conflict with the expectations of ERC20 applications.\n *\n * Additionally, an {Approval} event is emitted on calls to {transferFrom}.\n * This allows applications to reconstruct the allowance for all accounts just\n * by listening to said events. Other implementations of the EIP may not emit\n * these events, as it isn't required by the specification.\n *\n * Finally, the non-standard {decreaseAllowance} and {increaseAllowance}\n * functions have been added to mitigate the well-known issues around setting\n * allowances. See {IERC20-approve}.\n */\ncontract ERC20 is Context, IERC20 {\n using SafeMath for uint256;\n\n mapping (address => uint256) private _balances;\n\n mapping (address => mapping (address => uint256)) private _allowances;\n\n uint256 private _totalSupply;\n\n string private _name;\n string private _symbol;\n uint8 private _decimals;\n\n /**\n * @dev Sets the values for {name} and {symbol}, initializes {decimals} with\n * a default value of 18.\n *\n * To select a different value for {decimals}, use {_setupDecimals}.\n *\n * All three of these values are immutable: they can only be set once during\n * construction.\n */\n constructor (string memory name_, string memory symbol_) public {\n _name = name_;\n _symbol = symbol_;\n _decimals = 18;\n }\n\n /**\n * @dev Returns the name of the token.\n */\n function name() public view virtual returns (string memory) {\n return _name;\n }\n\n /**\n * @dev Returns the symbol of the token, usually a shorter version of the\n * name.\n */\n function symbol() public view virtual returns (string memory) {\n return _symbol;\n }\n\n /**\n * @dev Returns the number of decimals used to get its user representation.\n * For example, if `decimals` equals `2`, a balance of `505` tokens should\n * be displayed to a user as `5,05` (`505 / 10 ** 2`).\n *\n * Tokens usually opt for a value of 18, imitating the relationship between\n * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is\n * called.\n *\n * NOTE: This information is only used for _display_ purposes: it in\n * no way affects any of the arithmetic of the contract, including\n * {IERC20-balanceOf} and {IERC20-transfer}.\n */\n function decimals() public view virtual returns (uint8) {\n return _decimals;\n }\n\n /**\n * @dev See {IERC20-totalSupply}.\n */\n function totalSupply() public view virtual override returns (uint256) {\n return _totalSupply;\n }\n\n /**\n * @dev See {IERC20-balanceOf}.\n */\n function balanceOf(address account) public view virtual override returns (uint256) {\n return _balances[account];\n }\n\n /**\n * @dev See {IERC20-transfer}.\n *\n * Requirements:\n *\n * - `recipient` cannot be the zero address.\n * - the caller must have a balance of at least `amount`.\n */\n function transfer(address recipient, uint256 amount) public virtual override returns (bool) {\n _transfer(_msgSender(), recipient, amount);\n return true;\n }\n\n /**\n * @dev See {IERC20-allowance}.\n */\n function allowance(address owner, address spender) public view virtual override returns (uint256) {\n return _allowances[owner][spender];\n }\n\n /**\n * @dev See {IERC20-approve}.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n */\n function approve(address spender, uint256 amount) public virtual override returns (bool) {\n _approve(_msgSender(), spender, amount);\n return true;\n }\n\n /**\n * @dev See {IERC20-transferFrom}.\n *\n * Emits an {Approval} event indicating the updated allowance. This is not\n * required by the EIP. See the note at the beginning of {ERC20}.\n *\n * Requirements:\n *\n * - `sender` and `recipient` cannot be the zero address.\n * - `sender` must have a balance of at least `amount`.\n * - the caller must have allowance for ``sender``'s tokens of at least\n * `amount`.\n */\n function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {\n _transfer(sender, recipient, amount);\n _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, \"ERC20: transfer amount exceeds allowance\"));\n return true;\n }\n\n /**\n * @dev Atomically increases the allowance granted to `spender` by the caller.\n *\n * This is an alternative to {approve} that can be used as a mitigation for\n * problems described in {IERC20-approve}.\n *\n * Emits an {Approval} event indicating the updated allowance.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n */\n function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {\n _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));\n return true;\n }\n\n /**\n * @dev Atomically decreases the allowance granted to `spender` by the caller.\n *\n * This is an alternative to {approve} that can be used as a mitigation for\n * problems described in {IERC20-approve}.\n *\n * Emits an {Approval} event indicating the updated allowance.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n * - `spender` must have allowance for the caller of at least\n * `subtractedValue`.\n */\n function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {\n _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, \"ERC20: decreased allowance below zero\"));\n return true;\n }\n\n /**\n * @dev Moves tokens `amount` from `sender` to `recipient`.\n *\n * This is internal function is equivalent to {transfer}, and can be used to\n * e.g. implement automatic token fees, slashing mechanisms, etc.\n *\n * Emits a {Transfer} event.\n *\n * Requirements:\n *\n * - `sender` cannot be the zero address.\n * - `recipient` cannot be the zero address.\n * - `sender` must have a balance of at least `amount`.\n */\n function _transfer(address sender, address recipient, uint256 amount) internal virtual {\n require(sender != address(0), \"ERC20: transfer from the zero address\");\n require(recipient != address(0), \"ERC20: transfer to the zero address\");\n\n _beforeTokenTransfer(sender, recipient, amount);\n\n _balances[sender] = _balances[sender].sub(amount, \"ERC20: transfer amount exceeds balance\");\n _balances[recipient] = _balances[recipient].add(amount);\n emit Transfer(sender, recipient, amount);\n }\n\n /** @dev Creates `amount` tokens and assigns them to `account`, increasing\n * the total supply.\n *\n * Emits a {Transfer} event with `from` set to the zero address.\n *\n * Requirements:\n *\n * - `to` cannot be the zero address.\n */\n function _mint(address account, uint256 amount) internal virtual {\n require(account != address(0), \"ERC20: mint to the zero address\");\n\n _beforeTokenTransfer(address(0), account, amount);\n\n _totalSupply = _totalSupply.add(amount);\n _balances[account] = _balances[account].add(amount);\n emit Transfer(address(0), account, amount);\n }\n\n /**\n * @dev Destroys `amount` tokens from `account`, reducing the\n * total supply.\n *\n * Emits a {Transfer} event with `to` set to the zero address.\n *\n * Requirements:\n *\n * - `account` cannot be the zero address.\n * - `account` must have at least `amount` tokens.\n */\n function _burn(address account, uint256 amount) internal virtual {\n require(account != address(0), \"ERC20: burn from the zero address\");\n\n _beforeTokenTransfer(account, address(0), amount);\n\n _balances[account] = _balances[account].sub(amount, \"ERC20: burn amount exceeds balance\");\n _totalSupply = _totalSupply.sub(amount);\n emit Transfer(account, address(0), amount);\n }\n\n /**\n * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.\n *\n * This internal function is equivalent to `approve`, and can be used to\n * e.g. set automatic allowances for certain subsystems, etc.\n *\n * Emits an {Approval} event.\n *\n * Requirements:\n *\n * - `owner` cannot be the zero address.\n * - `spender` cannot be the zero address.\n */\n function _approve(address owner, address spender, uint256 amount) internal virtual {\n require(owner != address(0), \"ERC20: approve from the zero address\");\n require(spender != address(0), \"ERC20: approve to the zero address\");\n\n _allowances[owner][spender] = amount;\n emit Approval(owner, spender, amount);\n }\n\n /**\n * @dev Sets {decimals} to a value other than the default one of 18.\n *\n * WARNING: This function should only be called from the constructor. Most\n * applications that interact with token contracts will not expect\n * {decimals} to ever change, and may work incorrectly if it does.\n */\n function _setupDecimals(uint8 decimals_) internal virtual {\n _decimals = decimals_;\n }\n\n /**\n * @dev Hook that is called before any transfer of tokens. This includes\n * minting and burning.\n *\n * Calling conditions:\n *\n * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens\n * will be to transferred to `to`.\n * - when `from` is zero, `amount` tokens will be minted for `to`.\n * - when `to` is zero, `amount` of ``from``'s tokens will be burned.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }\n}\n"
|
|
},
|
|
"@openzeppelin/contracts/utils/Context.sol": {
|
|
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.6.0 <0.8.0;\n\n/*\n * @dev Provides information about the current execution context, including the\n * sender of the transaction and its data. While these are generally available\n * via msg.sender and msg.data, they should not be accessed in such a direct\n * manner, since when dealing with GSN meta-transactions the account sending and\n * paying for execution may not be the actual sender (as far as an application\n * is concerned).\n *\n * This contract is only required for intermediate, library-like contracts.\n */\nabstract contract Context {\n function _msgSender() internal view virtual returns (address payable) {\n return msg.sender;\n }\n\n function _msgData() internal view virtual returns (bytes memory) {\n this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691\n return msg.data;\n }\n}\n"
|
|
},
|
|
"contracts/mocks/ERC20Mock.sol": {
|
|
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity 0.6.12;\n\nimport \"@openzeppelin/contracts/token/ERC20/ERC20.sol\";\n\ncontract ERC20Mock is ERC20 {\n constructor(\n string memory name,\n string memory symbol,\n uint256 supply\n ) public ERC20(name, symbol) {\n _mint(msg.sender, supply);\n }\n}"
|
|
},
|
|
"contracts/SushiRoll.sol": {
|
|
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity 0.6.12;\n\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/SafeERC20.sol\";\nimport \"./uniswapv2/interfaces/IUniswapV2Pair.sol\";\nimport \"./uniswapv2/interfaces/IUniswapV2Router01.sol\";\nimport \"./uniswapv2/interfaces/IUniswapV2Factory.sol\";\nimport \"./uniswapv2/libraries/UniswapV2Library.sol\";\n\n// SushiRoll helps your migrate your existing Uniswap LP tokens to SushiSwap LP ones\ncontract SushiRoll {\n using SafeERC20 for IERC20;\n\n IUniswapV2Router01 public oldRouter;\n IUniswapV2Router01 public router;\n\n constructor(IUniswapV2Router01 _oldRouter, IUniswapV2Router01 _router) public {\n oldRouter = _oldRouter;\n router = _router;\n }\n\n function migrateWithPermit(\n address tokenA,\n address tokenB,\n uint256 liquidity,\n uint256 amountAMin,\n uint256 amountBMin,\n uint256 deadline,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) public {\n IUniswapV2Pair pair = IUniswapV2Pair(pairForOldRouter(tokenA, tokenB));\n pair.permit(msg.sender, address(this), liquidity, deadline, v, r, s);\n\n migrate(tokenA, tokenB, liquidity, amountAMin, amountBMin, deadline);\n }\n\n // msg.sender should have approved 'liquidity' amount of LP token of 'tokenA' and 'tokenB'\n function migrate(\n address tokenA,\n address tokenB,\n uint256 liquidity,\n uint256 amountAMin,\n uint256 amountBMin,\n uint256 deadline\n ) public {\n require(deadline >= block.timestamp, 'SushiSwap: EXPIRED');\n\n // Remove liquidity from the old router with permit\n (uint256 amountA, uint256 amountB) = removeLiquidity(\n tokenA,\n tokenB,\n liquidity,\n amountAMin,\n amountBMin,\n deadline\n );\n\n // Add liquidity to the new router\n (uint256 pooledAmountA, uint256 pooledAmountB) = addLiquidity(tokenA, tokenB, amountA, amountB);\n\n // Send remaining tokens to msg.sender\n if (amountA > pooledAmountA) {\n IERC20(tokenA).safeTransfer(msg.sender, amountA - pooledAmountA);\n }\n if (amountB > pooledAmountB) {\n IERC20(tokenB).safeTransfer(msg.sender, amountB - pooledAmountB);\n }\n }\n\n function removeLiquidity(\n address tokenA,\n address tokenB,\n uint256 liquidity,\n uint256 amountAMin,\n uint256 amountBMin,\n uint256 deadline\n ) internal returns (uint256 amountA, uint256 amountB) {\n IUniswapV2Pair pair = IUniswapV2Pair(pairForOldRouter(tokenA, tokenB));\n pair.transferFrom(msg.sender, address(pair), liquidity);\n (uint256 amount0, uint256 amount1) = pair.burn(address(this));\n (address token0,) = UniswapV2Library.sortTokens(tokenA, tokenB);\n (amountA, amountB) = tokenA == token0 ? (amount0, amount1) : (amount1, amount0);\n require(amountA >= amountAMin, 'SushiRoll: INSUFFICIENT_A_AMOUNT');\n require(amountB >= amountBMin, 'SushiRoll: INSUFFICIENT_B_AMOUNT');\n }\n\n // calculates the CREATE2 address for a pair without making any external calls\n function pairForOldRouter(address tokenA, address tokenB) internal view returns (address pair) {\n (address token0, address token1) = UniswapV2Library.sortTokens(tokenA, tokenB);\n pair = address(uint(keccak256(abi.encodePacked(\n hex'ff',\n oldRouter.factory(),\n keccak256(abi.encodePacked(token0, token1)),\n hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash\n ))));\n }\n\n function addLiquidity(\n address tokenA,\n address tokenB,\n uint256 amountADesired,\n uint256 amountBDesired\n ) internal returns (uint amountA, uint amountB) {\n (amountA, amountB) = _addLiquidity(tokenA, tokenB, amountADesired, amountBDesired);\n address pair = UniswapV2Library.pairFor(router.factory(), tokenA, tokenB);\n IERC20(tokenA).safeTransfer(pair, amountA);\n IERC20(tokenB).safeTransfer(pair, amountB);\n IUniswapV2Pair(pair).mint(msg.sender);\n }\n\n function _addLiquidity(\n address tokenA,\n address tokenB,\n uint256 amountADesired,\n uint256 amountBDesired\n ) internal returns (uint256 amountA, uint256 amountB) {\n // create the pair if it doesn't exist yet\n IUniswapV2Factory factory = IUniswapV2Factory(router.factory());\n if (factory.getPair(tokenA, tokenB) == address(0)) {\n factory.createPair(tokenA, tokenB);\n }\n (uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(address(factory), tokenA, tokenB);\n if (reserveA == 0 && reserveB == 0) {\n (amountA, amountB) = (amountADesired, amountBDesired);\n } else {\n uint256 amountBOptimal = UniswapV2Library.quote(amountADesired, reserveA, reserveB);\n if (amountBOptimal <= amountBDesired) {\n (amountA, amountB) = (amountADesired, amountBOptimal);\n } else {\n uint256 amountAOptimal = UniswapV2Library.quote(amountBDesired, reserveB, reserveA);\n assert(amountAOptimal <= amountADesired);\n (amountA, amountB) = (amountAOptimal, amountBDesired);\n }\n }\n }\n}\n"
|
|
},
|
|
"@openzeppelin/contracts/token/ERC20/SafeERC20.sol": {
|
|
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.6.0 <0.8.0;\n\nimport \"./IERC20.sol\";\nimport \"../../math/SafeMath.sol\";\nimport \"../../utils/Address.sol\";\n\n/**\n * @title SafeERC20\n * @dev Wrappers around ERC20 operations that throw on failure (when the token\n * contract returns false). Tokens that return no value (and instead revert or\n * throw on failure) are also supported, non-reverting calls are assumed to be\n * successful.\n * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,\n * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.\n */\nlibrary SafeERC20 {\n using SafeMath for uint256;\n using Address for address;\n\n function safeTransfer(IERC20 token, address to, uint256 value) internal {\n _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));\n }\n\n function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {\n _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));\n }\n\n /**\n * @dev Deprecated. This function has issues similar to the ones found in\n * {IERC20-approve}, and its usage is discouraged.\n *\n * Whenever possible, use {safeIncreaseAllowance} and\n * {safeDecreaseAllowance} instead.\n */\n function safeApprove(IERC20 token, address spender, uint256 value) internal {\n // safeApprove should only be called when setting an initial allowance,\n // or when resetting it to zero. To increase and decrease it, use\n // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'\n // solhint-disable-next-line max-line-length\n require((value == 0) || (token.allowance(address(this), spender) == 0),\n \"SafeERC20: approve from non-zero to non-zero allowance\"\n );\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));\n }\n\n function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {\n uint256 newAllowance = token.allowance(address(this), spender).add(value);\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));\n }\n\n function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {\n uint256 newAllowance = token.allowance(address(this), spender).sub(value, \"SafeERC20: decreased allowance below zero\");\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));\n }\n\n /**\n * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement\n * on the return value: the return value is optional (but if data is returned, it must not be false).\n * @param token The token targeted by the call.\n * @param data The call data (encoded using abi.encode or one of its variants).\n */\n function _callOptionalReturn(IERC20 token, bytes memory data) private {\n // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since\n // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that\n // the target address contains contract code and also asserts for success in the low-level call.\n\n bytes memory returndata = address(token).functionCall(data, \"SafeERC20: low-level call failed\");\n if (returndata.length > 0) { // Return data is optional\n // solhint-disable-next-line max-line-length\n require(abi.decode(returndata, (bool)), \"SafeERC20: ERC20 operation did not succeed\");\n }\n }\n}\n"
|
|
},
|
|
"contracts/uniswapv2/interfaces/IUniswapV2Pair.sol": {
|
|
"content": "// SPDX-License-Identifier: GPL-3.0\n\npragma solidity >=0.5.0;\n\ninterface IUniswapV2Pair {\n event Approval(address indexed owner, address indexed spender, uint value);\n event Transfer(address indexed from, address indexed to, uint value);\n\n function name() external pure returns (string memory);\n function symbol() external pure returns (string memory);\n function decimals() external pure returns (uint8);\n function totalSupply() external view returns (uint);\n function balanceOf(address owner) external view returns (uint);\n function allowance(address owner, address spender) external view returns (uint);\n\n function approve(address spender, uint value) external returns (bool);\n function transfer(address to, uint value) external returns (bool);\n function transferFrom(address from, address to, uint value) external returns (bool);\n\n function DOMAIN_SEPARATOR() external view returns (bytes32);\n function PERMIT_TYPEHASH() external pure returns (bytes32);\n function nonces(address owner) external view returns (uint);\n\n function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;\n\n event Mint(address indexed sender, uint amount0, uint amount1);\n event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);\n event Swap(\n address indexed sender,\n uint amount0In,\n uint amount1In,\n uint amount0Out,\n uint amount1Out,\n address indexed to\n );\n event Sync(uint112 reserve0, uint112 reserve1);\n\n function MINIMUM_LIQUIDITY() external pure returns (uint);\n function factory() external view returns (address);\n function token0() external view returns (address);\n function token1() external view returns (address);\n function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);\n function price0CumulativeLast() external view returns (uint);\n function price1CumulativeLast() external view returns (uint);\n function kLast() external view returns (uint);\n\n function mint(address to) external returns (uint liquidity);\n function burn(address to) external returns (uint amount0, uint amount1);\n function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;\n function skim(address to) external;\n function sync() external;\n\n function initialize(address, address) external;\n}"
|
|
},
|
|
"contracts/uniswapv2/interfaces/IUniswapV2Router01.sol": {
|
|
"content": "// SPDX-License-Identifier: GPL-3.0\n\npragma solidity >=0.6.2;\n\ninterface IUniswapV2Router01 {\n function factory() external pure returns (address);\n function WETH() external pure returns (address);\n\n function addLiquidity(\n address tokenA,\n address tokenB,\n uint amountADesired,\n uint amountBDesired,\n uint amountAMin,\n uint amountBMin,\n address to,\n uint deadline\n ) external returns (uint amountA, uint amountB, uint liquidity);\n function addLiquidityETH(\n address token,\n uint amountTokenDesired,\n uint amountTokenMin,\n uint amountETHMin,\n address to,\n uint deadline\n ) external payable returns (uint amountToken, uint amountETH, uint liquidity);\n function removeLiquidity(\n address tokenA,\n address tokenB,\n uint liquidity,\n uint amountAMin,\n uint amountBMin,\n address to,\n uint deadline\n ) external returns (uint amountA, uint amountB);\n function removeLiquidityETH(\n address token,\n uint liquidity,\n uint amountTokenMin,\n uint amountETHMin,\n address to,\n uint deadline\n ) external returns (uint amountToken, uint amountETH);\n function removeLiquidityWithPermit(\n address tokenA,\n address tokenB,\n uint liquidity,\n uint amountAMin,\n uint amountBMin,\n address to,\n uint deadline,\n bool approveMax, uint8 v, bytes32 r, bytes32 s\n ) external returns (uint amountA, uint amountB);\n function removeLiquidityETHWithPermit(\n address token,\n uint liquidity,\n uint amountTokenMin,\n uint amountETHMin,\n address to,\n uint deadline,\n bool approveMax, uint8 v, bytes32 r, bytes32 s\n ) external returns (uint amountToken, uint amountETH);\n function swapExactTokensForTokens(\n uint amountIn,\n uint amountOutMin,\n address[] calldata path,\n address to,\n uint deadline\n ) external returns (uint[] memory amounts);\n function swapTokensForExactTokens(\n uint amountOut,\n uint amountInMax,\n address[] calldata path,\n address to,\n uint deadline\n ) external returns (uint[] memory amounts);\n function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)\n external\n payable\n returns (uint[] memory amounts);\n function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)\n external\n returns (uint[] memory amounts);\n function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)\n external\n returns (uint[] memory amounts);\n function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)\n external\n payable\n returns (uint[] memory amounts);\n\n function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);\n function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);\n function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);\n function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);\n function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);\n}"
|
|
},
|
|
"contracts/uniswapv2/interfaces/IUniswapV2Factory.sol": {
|
|
"content": "// SPDX-License-Identifier: GPL-3.0\n\npragma solidity >=0.5.0;\n\ninterface IUniswapV2Factory {\n event PairCreated(address indexed token0, address indexed token1, address pair, uint);\n\n function feeTo() external view returns (address);\n function feeToSetter() external view returns (address);\n function migrator() external view returns (address);\n\n function getPair(address tokenA, address tokenB) external view returns (address pair);\n function allPairs(uint) external view returns (address pair);\n function allPairsLength() external view returns (uint);\n\n function createPair(address tokenA, address tokenB) external returns (address pair);\n\n function setFeeTo(address) external;\n function setFeeToSetter(address) external;\n function setMigrator(address) external;\n}\n"
|
|
},
|
|
"contracts/uniswapv2/libraries/UniswapV2Library.sol": {
|
|
"content": "// SPDX-License-Identifier: GPL-3.0\n\npragma solidity >=0.5.0;\n\nimport '../interfaces/IUniswapV2Pair.sol';\n\nimport \"./SafeMath.sol\";\n\nlibrary UniswapV2Library {\n using SafeMathUniswap for uint;\n\n // returns sorted token addresses, used to handle return values from pairs sorted in this order\n function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) {\n require(tokenA != tokenB, 'UniswapV2Library: IDENTICAL_ADDRESSES');\n (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);\n require(token0 != address(0), 'UniswapV2Library: ZERO_ADDRESS');\n }\n\n // calculates the CREATE2 address for a pair without making any external calls\n function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {\n (address token0, address token1) = sortTokens(tokenA, tokenB);\n pair = address(uint(keccak256(abi.encodePacked(\n hex'ff',\n factory,\n keccak256(abi.encodePacked(token0, token1)),\n hex'e18a34eb0e04b04f7a0ac29a6e80748dca96319b42c54d679cb821dca90c6303' // init code hash\n ))));\n }\n\n // fetches and sorts the reserves for a pair\n function getReserves(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) {\n (address token0,) = sortTokens(tokenA, tokenB);\n (uint reserve0, uint reserve1,) = IUniswapV2Pair(pairFor(factory, tokenA, tokenB)).getReserves();\n (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0);\n }\n\n // given some amount of an asset and pair reserves, returns an equivalent amount of the other asset\n function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) {\n require(amountA > 0, 'UniswapV2Library: INSUFFICIENT_AMOUNT');\n require(reserveA > 0 && reserveB > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');\n amountB = amountA.mul(reserveB) / reserveA;\n }\n\n // given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset\n function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) {\n require(amountIn > 0, 'UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT');\n require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');\n uint amountInWithFee = amountIn.mul(997);\n uint numerator = amountInWithFee.mul(reserveOut);\n uint denominator = reserveIn.mul(1000).add(amountInWithFee);\n amountOut = numerator / denominator;\n }\n\n // given an output amount of an asset and pair reserves, returns a required input amount of the other asset\n function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) {\n require(amountOut > 0, 'UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT');\n require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');\n uint numerator = reserveIn.mul(amountOut).mul(1000);\n uint denominator = reserveOut.sub(amountOut).mul(997);\n amountIn = (numerator / denominator).add(1);\n }\n\n // performs chained getAmountOut calculations on any number of pairs\n function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) {\n require(path.length >= 2, 'UniswapV2Library: INVALID_PATH');\n amounts = new uint[](path.length);\n amounts[0] = amountIn;\n for (uint i; i < path.length - 1; i++) {\n (uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]);\n amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut);\n }\n }\n\n // performs chained getAmountIn calculations on any number of pairs\n function getAmountsIn(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) {\n require(path.length >= 2, 'UniswapV2Library: INVALID_PATH');\n amounts = new uint[](path.length);\n amounts[amounts.length - 1] = amountOut;\n for (uint i = path.length - 1; i > 0; i--) {\n (uint reserveIn, uint reserveOut) = getReserves(factory, path[i - 1], path[i]);\n amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut);\n }\n }\n}\n"
|
|
},
|
|
"@openzeppelin/contracts/utils/Address.sol": {
|
|
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.6.2 <0.8.0;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary Address {\n /**\n * @dev Returns true if `account` is a contract.\n *\n * [IMPORTANT]\n * ====\n * It is unsafe to assume that an address for which this function returns\n * false is an externally-owned account (EOA) and not a contract.\n *\n * Among others, `isContract` will return false for the following\n * types of addresses:\n *\n * - an externally-owned account\n * - a contract in construction\n * - an address where a contract will be created\n * - an address where a contract lived, but was destroyed\n * ====\n */\n function isContract(address account) internal view returns (bool) {\n // This method relies on extcodesize, which returns 0 for contracts in\n // construction, since the code is only stored at the end of the\n // constructor execution.\n\n uint256 size;\n // solhint-disable-next-line no-inline-assembly\n assembly { size := extcodesize(account) }\n return size > 0;\n }\n\n /**\n * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\n * `recipient`, forwarding all available gas and reverting on errors.\n *\n * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n * of certain opcodes, possibly making contracts go over the 2300 gas limit\n * imposed by `transfer`, making them unable to receive funds via\n * `transfer`. {sendValue} removes this limitation.\n *\n * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n *\n * IMPORTANT: because control is transferred to `recipient`, care must be\n * taken to not create reentrancy vulnerabilities. Consider using\n * {ReentrancyGuard} or the\n * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n */\n function sendValue(address payable recipient, uint256 amount) internal {\n require(address(this).balance >= amount, \"Address: insufficient balance\");\n\n // solhint-disable-next-line avoid-low-level-calls, avoid-call-value\n (bool success, ) = recipient.call{ value: amount }(\"\");\n require(success, \"Address: unable to send value, recipient may have reverted\");\n }\n\n /**\n * @dev Performs a Solidity function call using a low level `call`. A\n * plain`call` is an unsafe replacement for a function call: use this\n * function instead.\n *\n * If `target` reverts with a revert reason, it is bubbled up by this\n * function (like regular Solidity function calls).\n *\n * Returns the raw returned data. To convert to the expected return value,\n * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n *\n * Requirements:\n *\n * - `target` must be a contract.\n * - calling `target` with `data` must not revert.\n *\n * _Available since v3.1._\n */\n function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionCall(target, data, \"Address: low-level call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with\n * `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {\n return functionCallWithValue(target, data, 0, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but also transferring `value` wei to `target`.\n *\n * Requirements:\n *\n * - the calling contract must have an ETH balance of at least `value`.\n * - the called Solidity function must be `payable`.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {\n return functionCallWithValue(target, data, value, \"Address: low-level call with value failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\n * with `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {\n require(address(this).balance >= value, \"Address: insufficient balance for call\");\n require(isContract(target), \"Address: call to non-contract\");\n\n // solhint-disable-next-line avoid-low-level-calls\n (bool success, bytes memory returndata) = target.call{ value: value }(data);\n return _verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n return functionStaticCall(target, data, \"Address: low-level static call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {\n require(isContract(target), \"Address: static call to non-contract\");\n\n // solhint-disable-next-line avoid-low-level-calls\n (bool success, bytes memory returndata) = target.staticcall(data);\n return _verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionDelegateCall(target, data, \"Address: low-level delegate call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {\n require(isContract(target), \"Address: delegate call to non-contract\");\n\n // solhint-disable-next-line avoid-low-level-calls\n (bool success, bytes memory returndata) = target.delegatecall(data);\n return _verifyCallResult(success, returndata, errorMessage);\n }\n\n function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {\n if (success) {\n return returndata;\n } else {\n // Look for revert reason and bubble it up if present\n if (returndata.length > 0) {\n // The easiest way to bubble the revert reason is using memory via assembly\n\n // solhint-disable-next-line no-inline-assembly\n assembly {\n let returndata_size := mload(returndata)\n revert(add(32, returndata), returndata_size)\n }\n } else {\n revert(errorMessage);\n }\n }\n }\n}\n"
|
|
},
|
|
"contracts/uniswapv2/libraries/SafeMath.sol": {
|
|
"content": "// SPDX-License-Identifier: GPL-3.0\n\npragma solidity =0.6.12;\n\n// a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math)\n\nlibrary SafeMathUniswap {\n function add(uint x, uint y) internal pure returns (uint z) {\n require((z = x + y) >= x, 'ds-math-add-overflow');\n }\n\n function sub(uint x, uint y) internal pure returns (uint z) {\n require((z = x - y) <= x, 'ds-math-sub-underflow');\n }\n\n function mul(uint x, uint y) internal pure returns (uint z) {\n require(y == 0 || (z = x * y) / y == x, 'ds-math-mul-overflow');\n }\n}\n"
|
|
},
|
|
"contracts/uniswapv2/UniswapV2Router02.sol": {
|
|
"content": "// SPDX-License-Identifier: GPL-3.0\n\npragma solidity =0.6.12;\n\nimport './libraries/UniswapV2Library.sol';\nimport './libraries/SafeMath.sol';\nimport './libraries/TransferHelper.sol';\nimport './interfaces/IUniswapV2Router02.sol';\nimport './interfaces/IUniswapV2Factory.sol';\nimport './interfaces/IERC20.sol';\nimport './interfaces/IWETH.sol';\n\ncontract UniswapV2Router02 is IUniswapV2Router02 {\n using SafeMathUniswap for uint;\n\n address public immutable override factory;\n address public immutable override WETH;\n\n modifier ensure(uint deadline) {\n require(deadline >= block.timestamp, 'UniswapV2Router: EXPIRED');\n _;\n }\n\n constructor(address _factory, address _WETH) public {\n factory = _factory;\n WETH = _WETH;\n }\n\n receive() external payable {\n assert(msg.sender == WETH); // only accept ETH via fallback from the WETH contract\n }\n\n // **** ADD LIQUIDITY ****\n function _addLiquidity(\n address tokenA,\n address tokenB,\n uint amountADesired,\n uint amountBDesired,\n uint amountAMin,\n uint amountBMin\n ) internal virtual returns (uint amountA, uint amountB) {\n // create the pair if it doesn't exist yet\n if (IUniswapV2Factory(factory).getPair(tokenA, tokenB) == address(0)) {\n IUniswapV2Factory(factory).createPair(tokenA, tokenB);\n }\n (uint reserveA, uint reserveB) = UniswapV2Library.getReserves(factory, tokenA, tokenB);\n if (reserveA == 0 && reserveB == 0) {\n (amountA, amountB) = (amountADesired, amountBDesired);\n } else {\n uint amountBOptimal = UniswapV2Library.quote(amountADesired, reserveA, reserveB);\n if (amountBOptimal <= amountBDesired) {\n require(amountBOptimal >= amountBMin, 'UniswapV2Router: INSUFFICIENT_B_AMOUNT');\n (amountA, amountB) = (amountADesired, amountBOptimal);\n } else {\n uint amountAOptimal = UniswapV2Library.quote(amountBDesired, reserveB, reserveA);\n assert(amountAOptimal <= amountADesired);\n require(amountAOptimal >= amountAMin, 'UniswapV2Router: INSUFFICIENT_A_AMOUNT');\n (amountA, amountB) = (amountAOptimal, amountBDesired);\n }\n }\n }\n function addLiquidity(\n address tokenA,\n address tokenB,\n uint amountADesired,\n uint amountBDesired,\n uint amountAMin,\n uint amountBMin,\n address to,\n uint deadline\n ) external virtual override ensure(deadline) returns (uint amountA, uint amountB, uint liquidity) {\n (amountA, amountB) = _addLiquidity(tokenA, tokenB, amountADesired, amountBDesired, amountAMin, amountBMin);\n address pair = UniswapV2Library.pairFor(factory, tokenA, tokenB);\n TransferHelper.safeTransferFrom(tokenA, msg.sender, pair, amountA);\n TransferHelper.safeTransferFrom(tokenB, msg.sender, pair, amountB);\n liquidity = IUniswapV2Pair(pair).mint(to);\n }\n function addLiquidityETH(\n address token,\n uint amountTokenDesired,\n uint amountTokenMin,\n uint amountETHMin,\n address to,\n uint deadline\n ) external virtual override payable ensure(deadline) returns (uint amountToken, uint amountETH, uint liquidity) {\n (amountToken, amountETH) = _addLiquidity(\n token,\n WETH,\n amountTokenDesired,\n msg.value,\n amountTokenMin,\n amountETHMin\n );\n address pair = UniswapV2Library.pairFor(factory, token, WETH);\n TransferHelper.safeTransferFrom(token, msg.sender, pair, amountToken);\n IWETH(WETH).deposit{value: amountETH}();\n assert(IWETH(WETH).transfer(pair, amountETH));\n liquidity = IUniswapV2Pair(pair).mint(to);\n // refund dust eth, if any\n if (msg.value > amountETH) TransferHelper.safeTransferETH(msg.sender, msg.value - amountETH);\n }\n\n // **** REMOVE LIQUIDITY ****\n function removeLiquidity(\n address tokenA,\n address tokenB,\n uint liquidity,\n uint amountAMin,\n uint amountBMin,\n address to,\n uint deadline\n ) public virtual override ensure(deadline) returns (uint amountA, uint amountB) {\n address pair = UniswapV2Library.pairFor(factory, tokenA, tokenB);\n IUniswapV2Pair(pair).transferFrom(msg.sender, pair, liquidity); // send liquidity to pair\n (uint amount0, uint amount1) = IUniswapV2Pair(pair).burn(to);\n (address token0,) = UniswapV2Library.sortTokens(tokenA, tokenB);\n (amountA, amountB) = tokenA == token0 ? (amount0, amount1) : (amount1, amount0);\n require(amountA >= amountAMin, 'UniswapV2Router: INSUFFICIENT_A_AMOUNT');\n require(amountB >= amountBMin, 'UniswapV2Router: INSUFFICIENT_B_AMOUNT');\n }\n function removeLiquidityETH(\n address token,\n uint liquidity,\n uint amountTokenMin,\n uint amountETHMin,\n address to,\n uint deadline\n ) public virtual override ensure(deadline) returns (uint amountToken, uint amountETH) {\n (amountToken, amountETH) = removeLiquidity(\n token,\n WETH,\n liquidity,\n amountTokenMin,\n amountETHMin,\n address(this),\n deadline\n );\n TransferHelper.safeTransfer(token, to, amountToken);\n IWETH(WETH).withdraw(amountETH);\n TransferHelper.safeTransferETH(to, amountETH);\n }\n function removeLiquidityWithPermit(\n address tokenA,\n address tokenB,\n uint liquidity,\n uint amountAMin,\n uint amountBMin,\n address to,\n uint deadline,\n bool approveMax, uint8 v, bytes32 r, bytes32 s\n ) external virtual override returns (uint amountA, uint amountB) {\n address pair = UniswapV2Library.pairFor(factory, tokenA, tokenB);\n uint value = approveMax ? uint(-1) : liquidity;\n IUniswapV2Pair(pair).permit(msg.sender, address(this), value, deadline, v, r, s);\n (amountA, amountB) = removeLiquidity(tokenA, tokenB, liquidity, amountAMin, amountBMin, to, deadline);\n }\n function removeLiquidityETHWithPermit(\n address token,\n uint liquidity,\n uint amountTokenMin,\n uint amountETHMin,\n address to,\n uint deadline,\n bool approveMax, uint8 v, bytes32 r, bytes32 s\n ) external virtual override returns (uint amountToken, uint amountETH) {\n address pair = UniswapV2Library.pairFor(factory, token, WETH);\n uint value = approveMax ? uint(-1) : liquidity;\n IUniswapV2Pair(pair).permit(msg.sender, address(this), value, deadline, v, r, s);\n (amountToken, amountETH) = removeLiquidityETH(token, liquidity, amountTokenMin, amountETHMin, to, deadline);\n }\n\n // **** REMOVE LIQUIDITY (supporting fee-on-transfer tokens) ****\n function removeLiquidityETHSupportingFeeOnTransferTokens(\n address token,\n uint liquidity,\n uint amountTokenMin,\n uint amountETHMin,\n address to,\n uint deadline\n ) public virtual override ensure(deadline) returns (uint amountETH) {\n (, amountETH) = removeLiquidity(\n token,\n WETH,\n liquidity,\n amountTokenMin,\n amountETHMin,\n address(this),\n deadline\n );\n TransferHelper.safeTransfer(token, to, IERC20Uniswap(token).balanceOf(address(this)));\n IWETH(WETH).withdraw(amountETH);\n TransferHelper.safeTransferETH(to, amountETH);\n }\n function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(\n address token,\n uint liquidity,\n uint amountTokenMin,\n uint amountETHMin,\n address to,\n uint deadline,\n bool approveMax, uint8 v, bytes32 r, bytes32 s\n ) external virtual override returns (uint amountETH) {\n address pair = UniswapV2Library.pairFor(factory, token, WETH);\n uint value = approveMax ? uint(-1) : liquidity;\n IUniswapV2Pair(pair).permit(msg.sender, address(this), value, deadline, v, r, s);\n amountETH = removeLiquidityETHSupportingFeeOnTransferTokens(\n token, liquidity, amountTokenMin, amountETHMin, to, deadline\n );\n }\n\n // **** SWAP ****\n // requires the initial amount to have already been sent to the first pair\n function _swap(uint[] memory amounts, address[] memory path, address _to) internal virtual {\n for (uint i; i < path.length - 1; i++) {\n (address input, address output) = (path[i], path[i + 1]);\n (address token0,) = UniswapV2Library.sortTokens(input, output);\n uint amountOut = amounts[i + 1];\n (uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOut) : (amountOut, uint(0));\n address to = i < path.length - 2 ? UniswapV2Library.pairFor(factory, output, path[i + 2]) : _to;\n IUniswapV2Pair(UniswapV2Library.pairFor(factory, input, output)).swap(\n amount0Out, amount1Out, to, new bytes(0)\n );\n }\n }\n function swapExactTokensForTokens(\n uint amountIn,\n uint amountOutMin,\n address[] calldata path,\n address to,\n uint deadline\n ) external virtual override ensure(deadline) returns (uint[] memory amounts) {\n amounts = UniswapV2Library.getAmountsOut(factory, amountIn, path);\n require(amounts[amounts.length - 1] >= amountOutMin, 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT');\n TransferHelper.safeTransferFrom(\n path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]\n );\n _swap(amounts, path, to);\n }\n function swapTokensForExactTokens(\n uint amountOut,\n uint amountInMax,\n address[] calldata path,\n address to,\n uint deadline\n ) external virtual override ensure(deadline) returns (uint[] memory amounts) {\n amounts = UniswapV2Library.getAmountsIn(factory, amountOut, path);\n require(amounts[0] <= amountInMax, 'UniswapV2Router: EXCESSIVE_INPUT_AMOUNT');\n TransferHelper.safeTransferFrom(\n path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]\n );\n _swap(amounts, path, to);\n }\n function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)\n external\n virtual\n override\n payable\n ensure(deadline)\n returns (uint[] memory amounts)\n {\n require(path[0] == WETH, 'UniswapV2Router: INVALID_PATH');\n amounts = UniswapV2Library.getAmountsOut(factory, msg.value, path);\n require(amounts[amounts.length - 1] >= amountOutMin, 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT');\n IWETH(WETH).deposit{value: amounts[0]}();\n assert(IWETH(WETH).transfer(UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]));\n _swap(amounts, path, to);\n }\n function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)\n external\n virtual\n override\n ensure(deadline)\n returns (uint[] memory amounts)\n {\n require(path[path.length - 1] == WETH, 'UniswapV2Router: INVALID_PATH');\n amounts = UniswapV2Library.getAmountsIn(factory, amountOut, path);\n require(amounts[0] <= amountInMax, 'UniswapV2Router: EXCESSIVE_INPUT_AMOUNT');\n TransferHelper.safeTransferFrom(\n path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]\n );\n _swap(amounts, path, address(this));\n IWETH(WETH).withdraw(amounts[amounts.length - 1]);\n TransferHelper.safeTransferETH(to, amounts[amounts.length - 1]);\n }\n function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)\n external\n virtual\n override\n ensure(deadline)\n returns (uint[] memory amounts)\n {\n require(path[path.length - 1] == WETH, 'UniswapV2Router: INVALID_PATH');\n amounts = UniswapV2Library.getAmountsOut(factory, amountIn, path);\n require(amounts[amounts.length - 1] >= amountOutMin, 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT');\n TransferHelper.safeTransferFrom(\n path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]\n );\n _swap(amounts, path, address(this));\n IWETH(WETH).withdraw(amounts[amounts.length - 1]);\n TransferHelper.safeTransferETH(to, amounts[amounts.length - 1]);\n }\n function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)\n external\n virtual\n override\n payable\n ensure(deadline)\n returns (uint[] memory amounts)\n {\n require(path[0] == WETH, 'UniswapV2Router: INVALID_PATH');\n amounts = UniswapV2Library.getAmountsIn(factory, amountOut, path);\n require(amounts[0] <= msg.value, 'UniswapV2Router: EXCESSIVE_INPUT_AMOUNT');\n IWETH(WETH).deposit{value: amounts[0]}();\n assert(IWETH(WETH).transfer(UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]));\n _swap(amounts, path, to);\n // refund dust eth, if any\n if (msg.value > amounts[0]) TransferHelper.safeTransferETH(msg.sender, msg.value - amounts[0]);\n }\n\n // **** SWAP (supporting fee-on-transfer tokens) ****\n // requires the initial amount to have already been sent to the first pair\n function _swapSupportingFeeOnTransferTokens(address[] memory path, address _to) internal virtual {\n for (uint i; i < path.length - 1; i++) {\n (address input, address output) = (path[i], path[i + 1]);\n (address token0,) = UniswapV2Library.sortTokens(input, output);\n IUniswapV2Pair pair = IUniswapV2Pair(UniswapV2Library.pairFor(factory, input, output));\n uint amountInput;\n uint amountOutput;\n { // scope to avoid stack too deep errors\n (uint reserve0, uint reserve1,) = pair.getReserves();\n (uint reserveInput, uint reserveOutput) = input == token0 ? (reserve0, reserve1) : (reserve1, reserve0);\n amountInput = IERC20Uniswap(input).balanceOf(address(pair)).sub(reserveInput);\n amountOutput = UniswapV2Library.getAmountOut(amountInput, reserveInput, reserveOutput);\n }\n (uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOutput) : (amountOutput, uint(0));\n address to = i < path.length - 2 ? UniswapV2Library.pairFor(factory, output, path[i + 2]) : _to;\n pair.swap(amount0Out, amount1Out, to, new bytes(0));\n }\n }\n function swapExactTokensForTokensSupportingFeeOnTransferTokens(\n uint amountIn,\n uint amountOutMin,\n address[] calldata path,\n address to,\n uint deadline\n ) external virtual override ensure(deadline) {\n TransferHelper.safeTransferFrom(\n path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amountIn\n );\n uint balanceBefore = IERC20Uniswap(path[path.length - 1]).balanceOf(to);\n _swapSupportingFeeOnTransferTokens(path, to);\n require(\n IERC20Uniswap(path[path.length - 1]).balanceOf(to).sub(balanceBefore) >= amountOutMin,\n 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT'\n );\n }\n function swapExactETHForTokensSupportingFeeOnTransferTokens(\n uint amountOutMin,\n address[] calldata path,\n address to,\n uint deadline\n )\n external\n virtual\n override\n payable\n ensure(deadline)\n {\n require(path[0] == WETH, 'UniswapV2Router: INVALID_PATH');\n uint amountIn = msg.value;\n IWETH(WETH).deposit{value: amountIn}();\n assert(IWETH(WETH).transfer(UniswapV2Library.pairFor(factory, path[0], path[1]), amountIn));\n uint balanceBefore = IERC20Uniswap(path[path.length - 1]).balanceOf(to);\n _swapSupportingFeeOnTransferTokens(path, to);\n require(\n IERC20Uniswap(path[path.length - 1]).balanceOf(to).sub(balanceBefore) >= amountOutMin,\n 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT'\n );\n }\n function swapExactTokensForETHSupportingFeeOnTransferTokens(\n uint amountIn,\n uint amountOutMin,\n address[] calldata path,\n address to,\n uint deadline\n )\n external\n virtual\n override\n ensure(deadline)\n {\n require(path[path.length - 1] == WETH, 'UniswapV2Router: INVALID_PATH');\n TransferHelper.safeTransferFrom(\n path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amountIn\n );\n _swapSupportingFeeOnTransferTokens(path, address(this));\n uint amountOut = IERC20Uniswap(WETH).balanceOf(address(this));\n require(amountOut >= amountOutMin, 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT');\n IWETH(WETH).withdraw(amountOut);\n TransferHelper.safeTransferETH(to, amountOut);\n }\n\n // **** LIBRARY FUNCTIONS ****\n function quote(uint amountA, uint reserveA, uint reserveB) public pure virtual override returns (uint amountB) {\n return UniswapV2Library.quote(amountA, reserveA, reserveB);\n }\n\n function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut)\n public\n pure\n virtual\n override\n returns (uint amountOut)\n {\n return UniswapV2Library.getAmountOut(amountIn, reserveIn, reserveOut);\n }\n\n function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut)\n public\n pure\n virtual\n override\n returns (uint amountIn)\n {\n return UniswapV2Library.getAmountIn(amountOut, reserveIn, reserveOut);\n }\n\n function getAmountsOut(uint amountIn, address[] memory path)\n public\n view\n virtual\n override\n returns (uint[] memory amounts)\n {\n return UniswapV2Library.getAmountsOut(factory, amountIn, path);\n }\n\n function getAmountsIn(uint amountOut, address[] memory path)\n public\n view\n virtual\n override\n returns (uint[] memory amounts)\n {\n return UniswapV2Library.getAmountsIn(factory, amountOut, path);\n }\n}\n"
|
|
},
|
|
"contracts/uniswapv2/libraries/TransferHelper.sol": {
|
|
"content": "// SPDX-License-Identifier: GPL-3.0\n\npragma solidity >=0.6.0;\n\n// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false\nlibrary TransferHelper {\n function safeApprove(address token, address to, uint value) internal {\n // bytes4(keccak256(bytes('approve(address,uint256)')));\n (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));\n require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED');\n }\n\n function safeTransfer(address token, address to, uint value) internal {\n // bytes4(keccak256(bytes('transfer(address,uint256)')));\n (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));\n require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED');\n }\n\n function safeTransferFrom(address token, address from, address to, uint value) internal {\n // bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));\n (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));\n require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED');\n }\n\n function safeTransferETH(address to, uint value) internal {\n (bool success,) = to.call{value:value}(new bytes(0));\n require(success, 'TransferHelper: ETH_TRANSFER_FAILED');\n }\n}\n"
|
|
},
|
|
"contracts/uniswapv2/interfaces/IUniswapV2Router02.sol": {
|
|
"content": "// SPDX-License-Identifier: GPL-3.0\n\npragma solidity >=0.6.2;\n\nimport './IUniswapV2Router01.sol';\n\ninterface IUniswapV2Router02 is IUniswapV2Router01 {\n function removeLiquidityETHSupportingFeeOnTransferTokens(\n address token,\n uint liquidity,\n uint amountTokenMin,\n uint amountETHMin,\n address to,\n uint deadline\n ) external returns (uint amountETH);\n function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(\n address token,\n uint liquidity,\n uint amountTokenMin,\n uint amountETHMin,\n address to,\n uint deadline,\n bool approveMax, uint8 v, bytes32 r, bytes32 s\n ) external returns (uint amountETH);\n\n function swapExactTokensForTokensSupportingFeeOnTransferTokens(\n uint amountIn,\n uint amountOutMin,\n address[] calldata path,\n address to,\n uint deadline\n ) external;\n function swapExactETHForTokensSupportingFeeOnTransferTokens(\n uint amountOutMin,\n address[] calldata path,\n address to,\n uint deadline\n ) external payable;\n function swapExactTokensForETHSupportingFeeOnTransferTokens(\n uint amountIn,\n uint amountOutMin,\n address[] calldata path,\n address to,\n uint deadline\n ) external;\n}"
|
|
},
|
|
"contracts/uniswapv2/interfaces/IERC20.sol": {
|
|
"content": "// SPDX-License-Identifier: GPL-3.0\n\npragma solidity >=0.5.0;\n\ninterface IERC20Uniswap {\n event Approval(address indexed owner, address indexed spender, uint value);\n event Transfer(address indexed from, address indexed to, uint value);\n\n function name() external view returns (string memory);\n function symbol() external view returns (string memory);\n function decimals() external view returns (uint8);\n function totalSupply() external view returns (uint);\n function balanceOf(address owner) external view returns (uint);\n function allowance(address owner, address spender) external view returns (uint);\n\n function approve(address spender, uint value) external returns (bool);\n function transfer(address to, uint value) external returns (bool);\n function transferFrom(address from, address to, uint value) external returns (bool);\n}\n"
|
|
},
|
|
"contracts/uniswapv2/interfaces/IWETH.sol": {
|
|
"content": "// SPDX-License-Identifier: GPL-3.0\n\npragma solidity >=0.5.0;\n\ninterface IWETH {\n function deposit() external payable;\n function transfer(address to, uint value) external returns (bool);\n function withdraw(uint) external;\n}"
|
|
},
|
|
"contracts/uniswapv2/UniswapV2Pair.sol": {
|
|
"content": "// SPDX-License-Identifier: GPL-3.0\n\npragma solidity =0.6.12;\n\nimport './UniswapV2ERC20.sol';\nimport './libraries/Math.sol';\nimport './libraries/UQ112x112.sol';\nimport './interfaces/IERC20.sol';\nimport './interfaces/IUniswapV2Factory.sol';\nimport './interfaces/IUniswapV2Callee.sol';\n\ninterface IMigrator {\n // Return the desired amount of liquidity token that the migrator wants.\n function desiredLiquidity() external view returns (uint256);\n}\n\ncontract UniswapV2Pair is UniswapV2ERC20 {\n using SafeMathUniswap for uint;\n using UQ112x112 for uint224;\n\n uint public constant MINIMUM_LIQUIDITY = 10**3;\n bytes4 private constant SELECTOR = bytes4(keccak256(bytes('transfer(address,uint256)')));\n\n address public factory;\n address public token0;\n address public token1;\n\n uint112 private reserve0; // uses single storage slot, accessible via getReserves\n uint112 private reserve1; // uses single storage slot, accessible via getReserves\n uint32 private blockTimestampLast; // uses single storage slot, accessible via getReserves\n\n uint public price0CumulativeLast;\n uint public price1CumulativeLast;\n uint public kLast; // reserve0 * reserve1, as of immediately after the most recent liquidity event\n\n uint private unlocked = 1;\n modifier lock() {\n require(unlocked == 1, 'UniswapV2: LOCKED');\n unlocked = 0;\n _;\n unlocked = 1;\n }\n\n function getReserves() public view returns (uint112 _reserve0, uint112 _reserve1, uint32 _blockTimestampLast) {\n _reserve0 = reserve0;\n _reserve1 = reserve1;\n _blockTimestampLast = blockTimestampLast;\n }\n\n function _safeTransfer(address token, address to, uint value) private {\n (bool success, bytes memory data) = token.call(abi.encodeWithSelector(SELECTOR, to, value));\n require(success && (data.length == 0 || abi.decode(data, (bool))), 'UniswapV2: TRANSFER_FAILED');\n }\n\n event Mint(address indexed sender, uint amount0, uint amount1);\n event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);\n event Swap(\n address indexed sender,\n uint amount0In,\n uint amount1In,\n uint amount0Out,\n uint amount1Out,\n address indexed to\n );\n event Sync(uint112 reserve0, uint112 reserve1);\n\n constructor() public {\n factory = msg.sender;\n }\n\n // called once by the factory at time of deployment\n function initialize(address _token0, address _token1) external {\n require(msg.sender == factory, 'UniswapV2: FORBIDDEN'); // sufficient check\n token0 = _token0;\n token1 = _token1;\n }\n\n // update reserves and, on the first call per block, price accumulators\n function _update(uint balance0, uint balance1, uint112 _reserve0, uint112 _reserve1) private {\n require(balance0 <= uint112(-1) && balance1 <= uint112(-1), 'UniswapV2: OVERFLOW');\n uint32 blockTimestamp = uint32(block.timestamp % 2**32);\n uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired\n if (timeElapsed > 0 && _reserve0 != 0 && _reserve1 != 0) {\n // * never overflows, and + overflow is desired\n price0CumulativeLast += uint(UQ112x112.encode(_reserve1).uqdiv(_reserve0)) * timeElapsed;\n price1CumulativeLast += uint(UQ112x112.encode(_reserve0).uqdiv(_reserve1)) * timeElapsed;\n }\n reserve0 = uint112(balance0);\n reserve1 = uint112(balance1);\n blockTimestampLast = blockTimestamp;\n emit Sync(reserve0, reserve1);\n }\n\n // if fee is on, mint liquidity equivalent to 1/6th of the growth in sqrt(k)\n function _mintFee(uint112 _reserve0, uint112 _reserve1) private returns (bool feeOn) {\n address feeTo = IUniswapV2Factory(factory).feeTo();\n feeOn = feeTo != address(0);\n uint _kLast = kLast; // gas savings\n if (feeOn) {\n if (_kLast != 0) {\n uint rootK = Math.sqrt(uint(_reserve0).mul(_reserve1));\n uint rootKLast = Math.sqrt(_kLast);\n if (rootK > rootKLast) {\n uint numerator = totalSupply.mul(rootK.sub(rootKLast));\n uint denominator = rootK.mul(5).add(rootKLast);\n uint liquidity = numerator / denominator;\n if (liquidity > 0) _mint(feeTo, liquidity);\n }\n }\n } else if (_kLast != 0) {\n kLast = 0;\n }\n }\n\n // this low-level function should be called from a contract which performs important safety checks\n function mint(address to) external lock returns (uint liquidity) {\n (uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings\n uint balance0 = IERC20Uniswap(token0).balanceOf(address(this));\n uint balance1 = IERC20Uniswap(token1).balanceOf(address(this));\n uint amount0 = balance0.sub(_reserve0);\n uint amount1 = balance1.sub(_reserve1);\n\n bool feeOn = _mintFee(_reserve0, _reserve1);\n uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee\n if (_totalSupply == 0) {\n address migrator = IUniswapV2Factory(factory).migrator();\n if (msg.sender == migrator) {\n liquidity = IMigrator(migrator).desiredLiquidity();\n require(liquidity > 0 && liquidity != uint256(-1), \"Bad desired liquidity\");\n } else {\n require(migrator == address(0), \"Must not have migrator\");\n liquidity = Math.sqrt(amount0.mul(amount1)).sub(MINIMUM_LIQUIDITY);\n _mint(address(0), MINIMUM_LIQUIDITY); // permanently lock the first MINIMUM_LIQUIDITY tokens\n }\n } else {\n liquidity = Math.min(amount0.mul(_totalSupply) / _reserve0, amount1.mul(_totalSupply) / _reserve1);\n }\n require(liquidity > 0, 'UniswapV2: INSUFFICIENT_LIQUIDITY_MINTED');\n _mint(to, liquidity);\n\n _update(balance0, balance1, _reserve0, _reserve1);\n if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date\n emit Mint(msg.sender, amount0, amount1);\n }\n\n // this low-level function should be called from a contract which performs important safety checks\n function burn(address to) external lock returns (uint amount0, uint amount1) {\n (uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings\n address _token0 = token0; // gas savings\n address _token1 = token1; // gas savings\n uint balance0 = IERC20Uniswap(_token0).balanceOf(address(this));\n uint balance1 = IERC20Uniswap(_token1).balanceOf(address(this));\n uint liquidity = balanceOf[address(this)];\n\n bool feeOn = _mintFee(_reserve0, _reserve1);\n uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee\n amount0 = liquidity.mul(balance0) / _totalSupply; // using balances ensures pro-rata distribution\n amount1 = liquidity.mul(balance1) / _totalSupply; // using balances ensures pro-rata distribution\n require(amount0 > 0 && amount1 > 0, 'UniswapV2: INSUFFICIENT_LIQUIDITY_BURNED');\n _burn(address(this), liquidity);\n _safeTransfer(_token0, to, amount0);\n _safeTransfer(_token1, to, amount1);\n balance0 = IERC20Uniswap(_token0).balanceOf(address(this));\n balance1 = IERC20Uniswap(_token1).balanceOf(address(this));\n\n _update(balance0, balance1, _reserve0, _reserve1);\n if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date\n emit Burn(msg.sender, amount0, amount1, to);\n }\n\n // this low-level function should be called from a contract which performs important safety checks\n function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external lock {\n require(amount0Out > 0 || amount1Out > 0, 'UniswapV2: INSUFFICIENT_OUTPUT_AMOUNT');\n (uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings\n require(amount0Out < _reserve0 && amount1Out < _reserve1, 'UniswapV2: INSUFFICIENT_LIQUIDITY');\n\n uint balance0;\n uint balance1;\n { // scope for _token{0,1}, avoids stack too deep errors\n address _token0 = token0;\n address _token1 = token1;\n require(to != _token0 && to != _token1, 'UniswapV2: INVALID_TO');\n if (amount0Out > 0) _safeTransfer(_token0, to, amount0Out); // optimistically transfer tokens\n if (amount1Out > 0) _safeTransfer(_token1, to, amount1Out); // optimistically transfer tokens\n if (data.length > 0) IUniswapV2Callee(to).uniswapV2Call(msg.sender, amount0Out, amount1Out, data);\n balance0 = IERC20Uniswap(_token0).balanceOf(address(this));\n balance1 = IERC20Uniswap(_token1).balanceOf(address(this));\n }\n uint amount0In = balance0 > _reserve0 - amount0Out ? balance0 - (_reserve0 - amount0Out) : 0;\n uint amount1In = balance1 > _reserve1 - amount1Out ? balance1 - (_reserve1 - amount1Out) : 0;\n require(amount0In > 0 || amount1In > 0, 'UniswapV2: INSUFFICIENT_INPUT_AMOUNT');\n { // scope for reserve{0,1}Adjusted, avoids stack too deep errors\n uint balance0Adjusted = balance0.mul(1000).sub(amount0In.mul(3));\n uint balance1Adjusted = balance1.mul(1000).sub(amount1In.mul(3));\n require(balance0Adjusted.mul(balance1Adjusted) >= uint(_reserve0).mul(_reserve1).mul(1000**2), 'UniswapV2: K');\n }\n\n _update(balance0, balance1, _reserve0, _reserve1);\n emit Swap(msg.sender, amount0In, amount1In, amount0Out, amount1Out, to);\n }\n\n // force balances to match reserves\n function skim(address to) external lock {\n address _token0 = token0; // gas savings\n address _token1 = token1; // gas savings\n _safeTransfer(_token0, to, IERC20Uniswap(_token0).balanceOf(address(this)).sub(reserve0));\n _safeTransfer(_token1, to, IERC20Uniswap(_token1).balanceOf(address(this)).sub(reserve1));\n }\n\n // force reserves to match balances\n function sync() external lock {\n _update(IERC20Uniswap(token0).balanceOf(address(this)), IERC20Uniswap(token1).balanceOf(address(this)), reserve0, reserve1);\n }\n}\n"
|
|
},
|
|
"contracts/uniswapv2/UniswapV2ERC20.sol": {
|
|
"content": "// SPDX-License-Identifier: GPL-3.0\n\npragma solidity =0.6.12;\n\nimport './libraries/SafeMath.sol';\n\ncontract UniswapV2ERC20 {\n using SafeMathUniswap for uint;\n\n string public constant name = 'SushiSwap LP Token';\n string public constant symbol = 'SLP';\n uint8 public constant decimals = 18;\n uint public totalSupply;\n mapping(address => uint) public balanceOf;\n mapping(address => mapping(address => uint)) public allowance;\n\n bytes32 public DOMAIN_SEPARATOR;\n // keccak256(\"Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)\");\n bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;\n mapping(address => uint) public nonces;\n\n event Approval(address indexed owner, address indexed spender, uint value);\n event Transfer(address indexed from, address indexed to, uint value);\n\n constructor() public {\n uint chainId;\n assembly {\n chainId := chainid()\n }\n DOMAIN_SEPARATOR = keccak256(\n abi.encode(\n keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'),\n keccak256(bytes(name)),\n keccak256(bytes('1')),\n chainId,\n address(this)\n )\n );\n }\n\n function _mint(address to, uint value) internal {\n totalSupply = totalSupply.add(value);\n balanceOf[to] = balanceOf[to].add(value);\n emit Transfer(address(0), to, value);\n }\n\n function _burn(address from, uint value) internal {\n balanceOf[from] = balanceOf[from].sub(value);\n totalSupply = totalSupply.sub(value);\n emit Transfer(from, address(0), value);\n }\n\n function _approve(address owner, address spender, uint value) private {\n allowance[owner][spender] = value;\n emit Approval(owner, spender, value);\n }\n\n function _transfer(address from, address to, uint value) private {\n balanceOf[from] = balanceOf[from].sub(value);\n balanceOf[to] = balanceOf[to].add(value);\n emit Transfer(from, to, value);\n }\n\n function approve(address spender, uint value) external returns (bool) {\n _approve(msg.sender, spender, value);\n return true;\n }\n\n function transfer(address to, uint value) external returns (bool) {\n _transfer(msg.sender, to, value);\n return true;\n }\n\n function transferFrom(address from, address to, uint value) external returns (bool) {\n if (allowance[from][msg.sender] != uint(-1)) {\n allowance[from][msg.sender] = allowance[from][msg.sender].sub(value);\n }\n _transfer(from, to, value);\n return true;\n }\n\n function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external {\n require(deadline >= block.timestamp, 'UniswapV2: EXPIRED');\n bytes32 digest = keccak256(\n abi.encodePacked(\n '\\x19\\x01',\n DOMAIN_SEPARATOR,\n keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline))\n )\n );\n address recoveredAddress = ecrecover(digest, v, r, s);\n require(recoveredAddress != address(0) && recoveredAddress == owner, 'UniswapV2: INVALID_SIGNATURE');\n _approve(owner, spender, value);\n }\n}\n"
|
|
},
|
|
"contracts/uniswapv2/libraries/Math.sol": {
|
|
"content": "// SPDX-License-Identifier: GPL-3.0\n\npragma solidity =0.6.12;\n\n// a library for performing various math operations\n\nlibrary Math {\n function min(uint x, uint y) internal pure returns (uint z) {\n z = x < y ? x : y;\n }\n\n // babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method)\n function sqrt(uint y) internal pure returns (uint z) {\n if (y > 3) {\n z = y;\n uint x = y / 2 + 1;\n while (x < z) {\n z = x;\n x = (y / x + x) / 2;\n }\n } else if (y != 0) {\n z = 1;\n }\n }\n}\n"
|
|
},
|
|
"contracts/uniswapv2/libraries/UQ112x112.sol": {
|
|
"content": "// SPDX-License-Identifier: GPL-3.0\n\npragma solidity =0.6.12;\n\n// a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format))\n\n// range: [0, 2**112 - 1]\n// resolution: 1 / 2**112\n\nlibrary UQ112x112 {\n uint224 constant Q112 = 2**112;\n\n // encode a uint112 as a UQ112x112\n function encode(uint112 y) internal pure returns (uint224 z) {\n z = uint224(y) * Q112; // never overflows\n }\n\n // divide a UQ112x112 by a uint112, returning a UQ112x112\n function uqdiv(uint224 x, uint112 y) internal pure returns (uint224 z) {\n z = x / uint224(y);\n }\n}\n"
|
|
},
|
|
"contracts/uniswapv2/interfaces/IUniswapV2Callee.sol": {
|
|
"content": "// SPDX-License-Identifier: GPL-3.0\n\npragma solidity >=0.5.0;\n\ninterface IUniswapV2Callee {\n function uniswapV2Call(address sender, uint amount0, uint amount1, bytes calldata data) external;\n}\n"
|
|
},
|
|
"contracts/mocks/SushiSwapPairMock.sol": {
|
|
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity 0.6.12;\n\nimport \"../uniswapv2/UniswapV2Pair.sol\";\n\ncontract SushiSwapPairMock is UniswapV2Pair {\n constructor() public UniswapV2Pair() {}\n}"
|
|
},
|
|
"contracts/uniswapv2/UniswapV2Factory.sol": {
|
|
"content": "// SPDX-License-Identifier: GPL-3.0\n\npragma solidity =0.6.12;\n\nimport './interfaces/IUniswapV2Factory.sol';\nimport './UniswapV2Pair.sol';\n\ncontract UniswapV2Factory is IUniswapV2Factory {\n address public override feeTo;\n address public override feeToSetter;\n address public override migrator;\n\n mapping(address => mapping(address => address)) public override getPair;\n address[] public override allPairs;\n\n event PairCreated(address indexed token0, address indexed token1, address pair, uint);\n\n constructor(address _feeToSetter) public {\n feeToSetter = _feeToSetter;\n }\n\n function allPairsLength() external override view returns (uint) {\n return allPairs.length;\n }\n\n function pairCodeHash() external pure returns (bytes32) {\n return keccak256(type(UniswapV2Pair).creationCode);\n }\n\n function createPair(address tokenA, address tokenB) external override returns (address pair) {\n require(tokenA != tokenB, 'UniswapV2: IDENTICAL_ADDRESSES');\n (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);\n require(token0 != address(0), 'UniswapV2: ZERO_ADDRESS');\n require(getPair[token0][token1] == address(0), 'UniswapV2: PAIR_EXISTS'); // single check is sufficient\n bytes memory bytecode = type(UniswapV2Pair).creationCode;\n bytes32 salt = keccak256(abi.encodePacked(token0, token1));\n assembly {\n pair := create2(0, add(bytecode, 32), mload(bytecode), salt)\n }\n UniswapV2Pair(pair).initialize(token0, token1);\n getPair[token0][token1] = pair;\n getPair[token1][token0] = pair; // populate mapping in the reverse direction\n allPairs.push(pair);\n emit PairCreated(token0, token1, pair, allPairs.length);\n }\n\n function setFeeTo(address _feeTo) external override {\n require(msg.sender == feeToSetter, 'UniswapV2: FORBIDDEN');\n feeTo = _feeTo;\n }\n\n function setMigrator(address _migrator) external override {\n require(msg.sender == feeToSetter, 'UniswapV2: FORBIDDEN');\n migrator = _migrator;\n }\n\n function setFeeToSetter(address _feeToSetter) external override {\n require(msg.sender == feeToSetter, 'UniswapV2: FORBIDDEN');\n feeToSetter = _feeToSetter;\n }\n\n}\n"
|
|
},
|
|
"contracts/mocks/SushiSwapFactoryMock.sol": {
|
|
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity 0.6.12;\n\nimport \"../uniswapv2/UniswapV2Factory.sol\";\n\ncontract SushiSwapFactoryMock is UniswapV2Factory {\n constructor(address _feeToSetter) public UniswapV2Factory(_feeToSetter) {}\n}"
|
|
},
|
|
"contracts/SushiMakerKashi.sol": {
|
|
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity 0.6.12;\nimport \"./libraries/SafeMath.sol\";\nimport \"./libraries/SafeERC20.sol\";\n\nimport \"./uniswapv2/interfaces/IUniswapV2Pair.sol\";\nimport \"./uniswapv2/interfaces/IUniswapV2Factory.sol\";\n\nimport \"./Ownable.sol\";\n\ninterface IBentoBoxWithdraw {\n function withdraw(\n IERC20 token_,\n address from,\n address to,\n uint256 amount,\n uint256 share\n ) external returns (uint256 amountOut, uint256 shareOut);\n}\n\ninterface IKashiWithdrawFee {\n function asset() external view returns (address);\n function balanceOf(address account) external view returns (uint256);\n function withdrawFees() external;\n function removeAsset(address to, uint256 fraction) external returns (uint256 share);\n}\n\n// SushiMakerKashi is MasterChef's left hand and kinda a wizard. He can cook up Sushi from pretty much anything!\n// This contract handles \"serving up\" rewards for xSushi holders by trading tokens collected from Kashi fees for Sushi.\ncontract SushiMakerKashi is Ownable {\n using SafeMath for uint256;\n using SafeERC20 for IERC20;\n\n IUniswapV2Factory private immutable factory;\n //0xC0AEe478e3658e2610c5F7A4A2E1777cE9e4f2Ac\n address private immutable bar;\n //0x8798249c2E607446EfB7Ad49eC89dD1865Ff4272\n IBentoBoxWithdraw private immutable bentoBox;\n //0xF5BCE5077908a1b7370B9ae04AdC565EBd643966 \n address private immutable sushi;\n //0x6B3595068778DD592e39A122f4f5a5cF09C90fE2\n address private immutable weth;\n //0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2\n bytes32 private immutable pairCodeHash;\n //0xe18a34eb0e04b04f7a0ac29a6e80748dca96319b42c54d679cb821dca90c6303\n\n mapping(address => address) private _bridges;\n\n event LogBridgeSet(address indexed token, address indexed bridge);\n event LogConvert(\n address indexed server,\n address indexed token0,\n uint256 amount0,\n uint256 amountBENTO,\n uint256 amountSUSHI\n );\n\n constructor(\n IUniswapV2Factory _factory,\n address _bar,\n IBentoBoxWithdraw _bentoBox,\n address _sushi,\n address _weth,\n bytes32 _pairCodeHash\n ) public {\n factory = _factory;\n bar = _bar;\n bentoBox = _bentoBox;\n sushi = _sushi;\n weth = _weth;\n pairCodeHash = _pairCodeHash;\n }\n\n function setBridge(address token, address bridge) external onlyOwner {\n // Checks\n require(\n token != sushi && token != weth && token != bridge,\n \"Maker: Invalid bridge\"\n );\n // Effects\n _bridges[token] = bridge;\n emit LogBridgeSet(token, bridge);\n }\n\n modifier onlyEOA() {\n // Try to make flash-loan exploit harder to do by only allowing externally-owned addresses.\n require(msg.sender == tx.origin, \"Maker: Must use EOA\");\n _;\n }\n\n function convert(IKashiWithdrawFee kashiPair) external onlyEOA {\n _convert(kashiPair);\n }\n\n function convertMultiple(IKashiWithdrawFee[] calldata kashiPair) external onlyEOA {\n for (uint256 i = 0; i < kashiPair.length; i++) {\n _convert(kashiPair[i]);\n }\n }\n\n function _convert(IKashiWithdrawFee kashiPair) private {\n // update Kashi fees for this Maker contract (`feeTo`)\n kashiPair.withdrawFees();\n\n // convert updated Kashi balance to Bento shares\n uint256 bentoShares = kashiPair.removeAsset(address(this), kashiPair.balanceOf(address(this)));\n\n // convert Bento shares to underlying Kashi asset (`token0`) balance (`amount0`) for Maker\n address token0 = kashiPair.asset();\n (uint256 amount0, ) = bentoBox.withdraw(IERC20(token0), address(this), address(this), 0, bentoShares);\n\n emit LogConvert(\n msg.sender,\n token0,\n amount0,\n bentoShares,\n _convertStep(token0, amount0)\n );\n }\n\n function _convertStep(address token0, uint256 amount0) private returns (uint256 sushiOut) {\n if (token0 == sushi) {\n IERC20(token0).safeTransfer(bar, amount0);\n sushiOut = amount0;\n } else if (token0 == weth) {\n sushiOut = _swap(token0, sushi, amount0, bar);\n } else {\n address bridge = _bridges[token0];\n if (bridge == address(0)) {\n bridge = weth;\n }\n uint256 amountOut = _swap(token0, bridge, amount0, address(this));\n sushiOut = _convertStep(bridge, amountOut);\n }\n }\n\n function _swap(\n address fromToken,\n address toToken,\n uint256 amountIn,\n address to\n ) private returns (uint256 amountOut) {\n (address token0, address token1) = fromToken < toToken ? (fromToken, toToken) : (toToken, fromToken);\n IUniswapV2Pair pair =\n IUniswapV2Pair(\n uint256(\n keccak256(abi.encodePacked(hex\"ff\", factory, keccak256(abi.encodePacked(token0, token1)), pairCodeHash))\n )\n );\n \n (uint256 reserve0, uint256 reserve1, ) = pair.getReserves();\n uint256 amountInWithFee = amountIn.mul(997);\n \n if (toToken > fromToken) {\n amountOut =\n amountInWithFee.mul(reserve1) /\n reserve0.mul(1000).add(amountInWithFee);\n IERC20(fromToken).safeTransfer(address(pair), amountIn);\n pair.swap(0, amountOut, to, \"\");\n } else {\n amountOut =\n amountInWithFee.mul(reserve0) /\n reserve1.mul(1000).add(amountInWithFee);\n IERC20(fromToken).safeTransfer(address(pair), amountIn);\n pair.swap(amountOut, 0, to, \"\");\n }\n }\n}\n"
|
|
},
|
|
"contracts/libraries/SafeMath.sol": {
|
|
"content": "// SPDX-License-Identifier: MIT\npragma solidity 0.6.12;\n// a library for performing overflow-safe math, updated with awesomeness from of DappHub (https://github.com/dapphub/ds-math)\nlibrary SafeMath {\n function add(uint256 a, uint256 b) internal pure returns (uint256 c) {require((c = a + b) >= b, \"SafeMath: Add Overflow\");}\n function sub(uint256 a, uint256 b) internal pure returns (uint256 c) {require((c = a - b) <= a, \"SafeMath: Underflow\");}\n function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {require(b == 0 || (c = a * b)/b == a, \"SafeMath: Mul Overflow\");}\n function to128(uint256 a) internal pure returns (uint128 c) {\n require(a <= uint128(-1), \"SafeMath: uint128 Overflow\");\n c = uint128(a);\n }\n}\n\nlibrary SafeMath128 {\n function add(uint128 a, uint128 b) internal pure returns (uint128 c) {require((c = a + b) >= b, \"SafeMath: Add Overflow\");}\n function sub(uint128 a, uint128 b) internal pure returns (uint128 c) {require((c = a - b) <= a, \"SafeMath: Underflow\");}\n}\n"
|
|
},
|
|
"contracts/libraries/SafeERC20.sol": {
|
|
"content": "// SPDX-License-Identifier: MIT\npragma solidity 0.6.12;\n\nimport \"../interfaces/IERC20.sol\";\n\nlibrary SafeERC20 {\n function safeSymbol(IERC20 token) internal view returns(string memory) {\n (bool success, bytes memory data) = address(token).staticcall(abi.encodeWithSelector(0x95d89b41));\n return success && data.length > 0 ? abi.decode(data, (string)) : \"???\";\n }\n\n function safeName(IERC20 token) internal view returns(string memory) {\n (bool success, bytes memory data) = address(token).staticcall(abi.encodeWithSelector(0x06fdde03));\n return success && data.length > 0 ? abi.decode(data, (string)) : \"???\";\n }\n\n function safeDecimals(IERC20 token) public view returns (uint8) {\n (bool success, bytes memory data) = address(token).staticcall(abi.encodeWithSelector(0x313ce567));\n return success && data.length == 32 ? abi.decode(data, (uint8)) : 18;\n }\n\n function safeTransfer(IERC20 token, address to, uint256 amount) internal {\n (bool success, bytes memory data) = address(token).call(abi.encodeWithSelector(0xa9059cbb, to, amount));\n require(success && (data.length == 0 || abi.decode(data, (bool))), \"SafeERC20: Transfer failed\");\n }\n\n function safeTransferFrom(IERC20 token, address from, uint256 amount) internal {\n (bool success, bytes memory data) = address(token).call(abi.encodeWithSelector(0x23b872dd, from, address(this), amount));\n require(success && (data.length == 0 || abi.decode(data, (bool))), \"SafeERC20: TransferFrom failed\");\n }\n}\n"
|
|
},
|
|
"contracts/Ownable.sol": {
|
|
"content": "// SPDX-License-Identifier: MIT\n// Audit on 5-Jan-2021 by Keno and BoringCrypto\n\n// P1 - P3: OK\npragma solidity 0.6.12;\n\n// Source: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/access/Ownable.sol + Claimable.sol\n// Edited by BoringCrypto\n\n// T1 - T4: OK\ncontract OwnableData {\n // V1 - V5: OK\n address public owner;\n // V1 - V5: OK\n address public pendingOwner;\n}\n\n// T1 - T4: OK\ncontract Ownable is OwnableData {\n // E1: OK\n event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);\n\n constructor () internal {\n owner = msg.sender;\n emit OwnershipTransferred(address(0), msg.sender);\n }\n\n // F1 - F9: OK\n // C1 - C21: OK\n function transferOwnership(address newOwner, bool direct, bool renounce) public onlyOwner {\n if (direct) {\n // Checks\n require(newOwner != address(0) || renounce, \"Ownable: zero address\");\n\n // Effects\n emit OwnershipTransferred(owner, newOwner);\n owner = newOwner;\n } else {\n // Effects\n pendingOwner = newOwner;\n }\n }\n\n // F1 - F9: OK\n // C1 - C21: OK\n function claimOwnership() public {\n address _pendingOwner = pendingOwner;\n\n // Checks\n require(msg.sender == _pendingOwner, \"Ownable: caller != pending owner\");\n\n // Effects\n emit OwnershipTransferred(owner, _pendingOwner);\n owner = _pendingOwner;\n pendingOwner = address(0);\n }\n\n // M1 - M5: OK\n // C1 - C21: OK\n modifier onlyOwner() {\n require(msg.sender == owner, \"Ownable: caller is not the owner\");\n _;\n }\n}\n"
|
|
},
|
|
"contracts/interfaces/IERC20.sol": {
|
|
"content": "// SPDX-License-Identifier: MIT\npragma solidity 0.6.12;\n\ninterface IERC20 {\n function totalSupply() external view returns (uint256);\n function balanceOf(address account) external view returns (uint256);\n function allowance(address owner, address spender) external view returns (uint256);\n function approve(address spender, uint256 amount) external returns (bool);\n event Transfer(address indexed from, address indexed to, uint256 value);\n event Approval(address indexed owner, address indexed spender, uint256 value);\n\n // EIP 2612\n function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external;\n}"
|
|
},
|
|
"contracts/SushiMaker.sol": {
|
|
"content": "// SPDX-License-Identifier: MIT\n\n// P1 - P3: OK\npragma solidity 0.6.12;\nimport \"./libraries/SafeMath.sol\";\nimport \"./libraries/SafeERC20.sol\";\n\nimport \"./uniswapv2/interfaces/IUniswapV2ERC20.sol\";\nimport \"./uniswapv2/interfaces/IUniswapV2Pair.sol\";\nimport \"./uniswapv2/interfaces/IUniswapV2Factory.sol\";\n\nimport \"./Ownable.sol\";\n\n// SushiMaker is MasterChef's left hand and kinda a wizard. He can cook up Sushi from pretty much anything!\n// This contract handles \"serving up\" rewards for xSushi holders by trading tokens collected from fees for Sushi.\n\n// T1 - T4: OK\ncontract SushiMaker is Ownable {\n using SafeMath for uint256;\n using SafeERC20 for IERC20;\n\n // V1 - V5: OK\n IUniswapV2Factory public immutable factory;\n //0xC0AEe478e3658e2610c5F7A4A2E1777cE9e4f2Ac\n // V1 - V5: OK\n address public immutable bar;\n //0x8798249c2E607446EfB7Ad49eC89dD1865Ff4272\n // V1 - V5: OK\n address private immutable sushi;\n //0x6B3595068778DD592e39A122f4f5a5cF09C90fE2\n // V1 - V5: OK\n address private immutable weth;\n //0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2\n\n // V1 - V5: OK\n mapping(address => address) internal _bridges;\n\n // E1: OK\n event LogBridgeSet(address indexed token, address indexed bridge);\n // E1: OK\n event LogConvert(\n address indexed server,\n address indexed token0,\n address indexed token1,\n uint256 amount0,\n uint256 amount1,\n uint256 amountSUSHI\n );\n\n constructor(\n address _factory,\n address _bar,\n address _sushi,\n address _weth\n ) public {\n factory = IUniswapV2Factory(_factory);\n bar = _bar;\n sushi = _sushi;\n weth = _weth;\n }\n\n // F1 - F10: OK\n // C1 - C24: OK\n function bridgeFor(address token) public view returns (address bridge) {\n bridge = _bridges[token];\n if (bridge == address(0)) {\n bridge = weth;\n }\n }\n\n // F1 - F10: OK\n // C1 - C24: OK\n function setBridge(address token, address bridge) external onlyOwner {\n // Checks\n require(\n token != sushi && token != weth && token != bridge,\n \"SushiMaker: Invalid bridge\"\n );\n\n // Effects\n _bridges[token] = bridge;\n emit LogBridgeSet(token, bridge);\n }\n\n // M1 - M5: OK\n // C1 - C24: OK\n // C6: It's not a fool proof solution, but it prevents flash loans, so here it's ok to use tx.origin\n modifier onlyEOA() {\n // Try to make flash-loan exploit harder to do by only allowing externally owned addresses.\n require(msg.sender == tx.origin, \"SushiMaker: must use EOA\");\n _;\n }\n\n // F1 - F10: OK\n // F3: _convert is separate to save gas by only checking the 'onlyEOA' modifier once in case of convertMultiple\n // F6: There is an exploit to add lots of SUSHI to the bar, run convert, then remove the SUSHI again.\n // As the size of the SushiBar has grown, this requires large amounts of funds and isn't super profitable anymore\n // The onlyEOA modifier prevents this being done with a flash loan.\n // C1 - C24: OK\n function convert(address token0, address token1) external onlyEOA() {\n _convert(token0, token1);\n }\n\n // F1 - F10: OK, see convert\n // C1 - C24: OK\n // C3: Loop is under control of the caller\n function convertMultiple(\n address[] calldata token0,\n address[] calldata token1\n ) external onlyEOA() {\n // TODO: This can be optimized a fair bit, but this is safer and simpler for now\n uint256 len = token0.length;\n for (uint256 i = 0; i < len; i++) {\n _convert(token0[i], token1[i]);\n }\n }\n\n // F1 - F10: OK\n // C1- C24: OK\n function _convert(address token0, address token1) internal {\n // Interactions\n // S1 - S4: OK\n IUniswapV2Pair pair = IUniswapV2Pair(factory.getPair(token0, token1));\n require(address(pair) != address(0), \"SushiMaker: Invalid pair\");\n // balanceOf: S1 - S4: OK\n // transfer: X1 - X5: OK\n IERC20(address(pair)).safeTransfer(\n address(pair),\n pair.balanceOf(address(this))\n );\n // X1 - X5: OK\n (uint256 amount0, uint256 amount1) = pair.burn(address(this));\n if (token0 != pair.token0()) {\n (amount0, amount1) = (amount1, amount0);\n }\n emit LogConvert(\n msg.sender,\n token0,\n token1,\n amount0,\n amount1,\n _convertStep(token0, token1, amount0, amount1)\n );\n }\n\n // F1 - F10: OK\n // C1 - C24: OK\n // All safeTransfer, _swap, _toSUSHI, _convertStep: X1 - X5: OK\n function _convertStep(\n address token0,\n address token1,\n uint256 amount0,\n uint256 amount1\n ) internal returns (uint256 sushiOut) {\n // Interactions\n if (token0 == token1) {\n uint256 amount = amount0.add(amount1);\n if (token0 == sushi) {\n IERC20(sushi).safeTransfer(bar, amount);\n sushiOut = amount;\n } else if (token0 == weth) {\n sushiOut = _toSUSHI(weth, amount);\n } else {\n address bridge = bridgeFor(token0);\n amount = _swap(token0, bridge, amount, address(this));\n sushiOut = _convertStep(bridge, bridge, amount, 0);\n }\n } else if (token0 == sushi) {\n // eg. SUSHI - ETH\n IERC20(sushi).safeTransfer(bar, amount0);\n sushiOut = _toSUSHI(token1, amount1).add(amount0);\n } else if (token1 == sushi) {\n // eg. USDT - SUSHI\n IERC20(sushi).safeTransfer(bar, amount1);\n sushiOut = _toSUSHI(token0, amount0).add(amount1);\n } else if (token0 == weth) {\n // eg. ETH - USDC\n sushiOut = _toSUSHI(\n weth,\n _swap(token1, weth, amount1, address(this)).add(amount0)\n );\n } else if (token1 == weth) {\n // eg. USDT - ETH\n sushiOut = _toSUSHI(\n weth,\n _swap(token0, weth, amount0, address(this)).add(amount1)\n );\n } else {\n // eg. MIC - USDT\n address bridge0 = bridgeFor(token0);\n address bridge1 = bridgeFor(token1);\n if (bridge0 == token1) {\n // eg. MIC - USDT - and bridgeFor(MIC) = USDT\n sushiOut = _convertStep(\n bridge0,\n token1,\n _swap(token0, bridge0, amount0, address(this)),\n amount1\n );\n } else if (bridge1 == token0) {\n // eg. WBTC - DSD - and bridgeFor(DSD) = WBTC\n sushiOut = _convertStep(\n token0,\n bridge1,\n amount0,\n _swap(token1, bridge1, amount1, address(this))\n );\n } else {\n sushiOut = _convertStep(\n bridge0,\n bridge1, // eg. USDT - DSD - and bridgeFor(DSD) = WBTC\n _swap(token0, bridge0, amount0, address(this)),\n _swap(token1, bridge1, amount1, address(this))\n );\n }\n }\n }\n\n // F1 - F10: OK\n // C1 - C24: OK\n // All safeTransfer, swap: X1 - X5: OK\n function _swap(\n address fromToken,\n address toToken,\n uint256 amountIn,\n address to\n ) internal returns (uint256 amountOut) {\n // Checks\n // X1 - X5: OK\n IUniswapV2Pair pair =\n IUniswapV2Pair(factory.getPair(fromToken, toToken));\n require(address(pair) != address(0), \"SushiMaker: Cannot convert\");\n\n // Interactions\n // X1 - X5: OK\n (uint256 reserve0, uint256 reserve1, ) = pair.getReserves();\n uint256 amountInWithFee = amountIn.mul(997);\n if (fromToken == pair.token0()) {\n amountOut =\n amountInWithFee.mul(reserve1) /\n reserve0.mul(1000).add(amountInWithFee);\n IERC20(fromToken).safeTransfer(address(pair), amountIn);\n pair.swap(0, amountOut, to, new bytes(0));\n // TODO: Add maximum slippage?\n } else {\n amountOut =\n amountInWithFee.mul(reserve0) /\n reserve1.mul(1000).add(amountInWithFee);\n IERC20(fromToken).safeTransfer(address(pair), amountIn);\n pair.swap(amountOut, 0, to, new bytes(0));\n // TODO: Add maximum slippage?\n }\n }\n\n // F1 - F10: OK\n // C1 - C24: OK\n function _toSUSHI(address token, uint256 amountIn)\n internal\n returns (uint256 amountOut)\n {\n // X1 - X5: OK\n amountOut = _swap(token, sushi, amountIn, bar);\n }\n}\n"
|
|
},
|
|
"contracts/uniswapv2/interfaces/IUniswapV2ERC20.sol": {
|
|
"content": "// SPDX-License-Identifier: GPL-3.0\n\npragma solidity >=0.5.0;\n\ninterface IUniswapV2ERC20 {\n event Approval(address indexed owner, address indexed spender, uint value);\n event Transfer(address indexed from, address indexed to, uint value);\n\n function name() external pure returns (string memory);\n function symbol() external pure returns (string memory);\n function decimals() external pure returns (uint8);\n function totalSupply() external view returns (uint);\n function balanceOf(address owner) external view returns (uint);\n function allowance(address owner, address spender) external view returns (uint);\n\n function approve(address spender, uint value) external returns (bool);\n function transfer(address to, uint value) external returns (bool);\n function transferFrom(address from, address to, uint value) external returns (bool);\n\n function DOMAIN_SEPARATOR() external view returns (bytes32);\n function PERMIT_TYPEHASH() external pure returns (bytes32);\n function nonces(address owner) external view returns (uint);\n\n function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;\n}"
|
|
},
|
|
"contracts/Migrator.sol": {
|
|
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity 0.6.12;\n\nimport \"./uniswapv2/interfaces/IUniswapV2Pair.sol\";\nimport \"./uniswapv2/interfaces/IUniswapV2Factory.sol\";\n\n\ncontract Migrator {\n address public chef;\n address public oldFactory;\n IUniswapV2Factory public factory;\n uint256 public notBeforeBlock;\n uint256 public desiredLiquidity = uint256(-1);\n\n constructor(\n address _chef,\n address _oldFactory,\n IUniswapV2Factory _factory,\n uint256 _notBeforeBlock\n ) public {\n chef = _chef;\n oldFactory = _oldFactory;\n factory = _factory;\n notBeforeBlock = _notBeforeBlock;\n }\n\n function migrate(IUniswapV2Pair orig) public returns (IUniswapV2Pair) {\n require(msg.sender == chef, \"not from master chef\");\n require(block.number >= notBeforeBlock, \"too early to migrate\");\n require(orig.factory() == oldFactory, \"not from old factory\");\n address token0 = orig.token0();\n address token1 = orig.token1();\n IUniswapV2Pair pair = IUniswapV2Pair(factory.getPair(token0, token1));\n if (pair == IUniswapV2Pair(address(0))) {\n pair = IUniswapV2Pair(factory.createPair(token0, token1));\n }\n uint256 lp = orig.balanceOf(msg.sender);\n if (lp == 0) return pair;\n desiredLiquidity = lp;\n orig.transferFrom(msg.sender, address(orig), lp);\n orig.burn(address(pair));\n pair.mint(msg.sender);\n desiredLiquidity = uint256(-1);\n return pair;\n }\n}"
|
|
},
|
|
"contracts/mocks/SushiMakerExploitMock.sol": {
|
|
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity 0.6.12;\n\nimport \"../SushiMaker.sol\";\n\ncontract SushiMakerExploitMock {\n SushiMaker public immutable sushiMaker;\n constructor (address _sushiMaker) public{\n sushiMaker = SushiMaker(_sushiMaker);\n } \n function convert(address token0, address token1) external {\n sushiMaker.convert(token0, token1);\n }\n}"
|
|
},
|
|
"contracts/mocks/SushiMakerKashiExploitMock.sol": {
|
|
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity 0.6.12;\n\nimport \"../SushiMakerKashi.sol\";\n\ncontract SushiMakerKashiExploitMock {\n SushiMakerKashi public immutable sushiMaker;\n \n constructor(address _sushiMaker) public {\n sushiMaker = SushiMakerKashi(_sushiMaker);\n } \n \n function convert(IKashiWithdrawFee kashiPair) external {\n sushiMaker.convert(kashiPair);\n }\n}\n"
|
|
},
|
|
"contracts/MasterChef.sol": {
|
|
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity 0.6.12;\n\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/SafeERC20.sol\";\nimport \"@openzeppelin/contracts/utils/EnumerableSet.sol\";\nimport \"@openzeppelin/contracts/math/SafeMath.sol\";\nimport \"@openzeppelin/contracts/access/Ownable.sol\";\nimport \"./SushiToken.sol\";\n\ninterface IMigratorChef {\n // Perform LP token migration from legacy UniswapV2 to SushiSwap.\n // Take the current LP token address and return the new LP token address.\n // Migrator should have full access to the caller's LP token.\n // Return the new LP token address.\n //\n // XXX Migrator must have allowance access to UniswapV2 LP tokens.\n // SushiSwap must mint EXACTLY the same amount of SushiSwap LP tokens or\n // else something bad will happen. Traditional UniswapV2 does not\n // do that so be careful!\n function migrate(IERC20 token) external returns (IERC20);\n}\n\n// MasterChef is the master of Sushi. He can make Sushi and he is a fair guy.\n//\n// Note that it's ownable and the owner wields tremendous power. The ownership\n// will be transferred to a governance smart contract once SUSHI is sufficiently\n// distributed and the community can show to govern itself.\n//\n// Have fun reading it. Hopefully it's bug-free. God bless.\ncontract MasterChef is Ownable {\n using SafeMath for uint256;\n using SafeERC20 for IERC20;\n // Info of each user.\n struct UserInfo {\n uint256 amount; // How many LP tokens the user has provided.\n uint256 rewardDebt; // Reward debt. See explanation below.\n //\n // We do some fancy math here. Basically, any point in time, the amount of SUSHIs\n // entitled to a user but is pending to be distributed is:\n //\n // pending reward = (user.amount * pool.accSushiPerShare) - user.rewardDebt\n //\n // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:\n // 1. The pool's `accSushiPerShare` (and `lastRewardBlock`) gets updated.\n // 2. User receives the pending reward sent to his/her address.\n // 3. User's `amount` gets updated.\n // 4. User's `rewardDebt` gets updated.\n }\n // Info of each pool.\n struct PoolInfo {\n IERC20 lpToken; // Address of LP token contract.\n uint256 allocPoint; // How many allocation points assigned to this pool. SUSHIs to distribute per block.\n uint256 lastRewardBlock; // Last block number that SUSHIs distribution occurs.\n uint256 accSushiPerShare; // Accumulated SUSHIs per share, times 1e12. See below.\n }\n // The SUSHI TOKEN!\n SushiToken public sushi;\n // Dev address.\n address public devaddr;\n // Block number when bonus SUSHI period ends.\n uint256 public bonusEndBlock;\n // SUSHI tokens created per block.\n uint256 public sushiPerBlock;\n // Bonus muliplier for early sushi makers.\n uint256 public constant BONUS_MULTIPLIER = 10;\n // The migrator contract. It has a lot of power. Can only be set through governance (owner).\n IMigratorChef public migrator;\n // Info of each pool.\n PoolInfo[] public poolInfo;\n // Info of each user that stakes LP tokens.\n mapping(uint256 => mapping(address => UserInfo)) public userInfo;\n // Total allocation poitns. Must be the sum of all allocation points in all pools.\n uint256 public totalAllocPoint = 0;\n // The block number when SUSHI mining starts.\n uint256 public startBlock;\n event Deposit(address indexed user, uint256 indexed pid, uint256 amount);\n event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);\n event EmergencyWithdraw(\n address indexed user,\n uint256 indexed pid,\n uint256 amount\n );\n\n constructor(\n SushiToken _sushi,\n address _devaddr,\n uint256 _sushiPerBlock,\n uint256 _startBlock,\n uint256 _bonusEndBlock\n ) public {\n sushi = _sushi;\n devaddr = _devaddr;\n sushiPerBlock = _sushiPerBlock;\n bonusEndBlock = _bonusEndBlock;\n startBlock = _startBlock;\n }\n\n function poolLength() external view returns (uint256) {\n return poolInfo.length;\n }\n\n // Add a new lp to the pool. Can only be called by the owner.\n // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do.\n function add(\n uint256 _allocPoint,\n IERC20 _lpToken,\n bool _withUpdate\n ) public onlyOwner {\n if (_withUpdate) {\n massUpdatePools();\n }\n uint256 lastRewardBlock =\n block.number > startBlock ? block.number : startBlock;\n totalAllocPoint = totalAllocPoint.add(_allocPoint);\n poolInfo.push(\n PoolInfo({\n lpToken: _lpToken,\n allocPoint: _allocPoint,\n lastRewardBlock: lastRewardBlock,\n accSushiPerShare: 0\n })\n );\n }\n\n // Update the given pool's SUSHI allocation point. Can only be called by the owner.\n function set(\n uint256 _pid,\n uint256 _allocPoint,\n bool _withUpdate\n ) public onlyOwner {\n if (_withUpdate) {\n massUpdatePools();\n }\n totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(\n _allocPoint\n );\n poolInfo[_pid].allocPoint = _allocPoint;\n }\n\n // Set the migrator contract. Can only be called by the owner.\n function setMigrator(IMigratorChef _migrator) public onlyOwner {\n migrator = _migrator;\n }\n\n // Migrate lp token to another lp contract. Can be called by anyone. We trust that migrator contract is good.\n function migrate(uint256 _pid) public {\n require(address(migrator) != address(0), \"migrate: no migrator\");\n PoolInfo storage pool = poolInfo[_pid];\n IERC20 lpToken = pool.lpToken;\n uint256 bal = lpToken.balanceOf(address(this));\n lpToken.safeApprove(address(migrator), bal);\n IERC20 newLpToken = migrator.migrate(lpToken);\n require(bal == newLpToken.balanceOf(address(this)), \"migrate: bad\");\n pool.lpToken = newLpToken;\n }\n\n // Return reward multiplier over the given _from to _to block.\n function getMultiplier(uint256 _from, uint256 _to)\n public\n view\n returns (uint256)\n {\n if (_to <= bonusEndBlock) {\n return _to.sub(_from).mul(BONUS_MULTIPLIER);\n } else if (_from >= bonusEndBlock) {\n return _to.sub(_from);\n } else {\n return\n bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add(\n _to.sub(bonusEndBlock)\n );\n }\n }\n\n // View function to see pending SUSHIs on frontend.\n function pendingSushi(uint256 _pid, address _user)\n external\n view\n returns (uint256)\n {\n PoolInfo storage pool = poolInfo[_pid];\n UserInfo storage user = userInfo[_pid][_user];\n uint256 accSushiPerShare = pool.accSushiPerShare;\n uint256 lpSupply = pool.lpToken.balanceOf(address(this));\n if (block.number > pool.lastRewardBlock && lpSupply != 0) {\n uint256 multiplier =\n getMultiplier(pool.lastRewardBlock, block.number);\n uint256 sushiReward =\n multiplier.mul(sushiPerBlock).mul(pool.allocPoint).div(\n totalAllocPoint\n );\n accSushiPerShare = accSushiPerShare.add(\n sushiReward.mul(1e12).div(lpSupply)\n );\n }\n return user.amount.mul(accSushiPerShare).div(1e12).sub(user.rewardDebt);\n }\n\n // Update reward vairables for all pools. Be careful of gas spending!\n function massUpdatePools() public {\n uint256 length = poolInfo.length;\n for (uint256 pid = 0; pid < length; ++pid) {\n updatePool(pid);\n }\n }\n\n // Update reward variables of the given pool to be up-to-date.\n function updatePool(uint256 _pid) public {\n PoolInfo storage pool = poolInfo[_pid];\n if (block.number <= pool.lastRewardBlock) {\n return;\n }\n uint256 lpSupply = pool.lpToken.balanceOf(address(this));\n if (lpSupply == 0) {\n pool.lastRewardBlock = block.number;\n return;\n }\n uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);\n uint256 sushiReward =\n multiplier.mul(sushiPerBlock).mul(pool.allocPoint).div(\n totalAllocPoint\n );\n sushi.mint(devaddr, sushiReward.div(10));\n sushi.mint(address(this), sushiReward);\n pool.accSushiPerShare = pool.accSushiPerShare.add(\n sushiReward.mul(1e12).div(lpSupply)\n );\n pool.lastRewardBlock = block.number;\n }\n\n // Deposit LP tokens to MasterChef for SUSHI allocation.\n function deposit(uint256 _pid, uint256 _amount) public {\n PoolInfo storage pool = poolInfo[_pid];\n UserInfo storage user = userInfo[_pid][msg.sender];\n updatePool(_pid);\n if (user.amount > 0) {\n uint256 pending =\n user.amount.mul(pool.accSushiPerShare).div(1e12).sub(\n user.rewardDebt\n );\n safeSushiTransfer(msg.sender, pending);\n }\n pool.lpToken.safeTransferFrom(\n address(msg.sender),\n address(this),\n _amount\n );\n user.amount = user.amount.add(_amount);\n user.rewardDebt = user.amount.mul(pool.accSushiPerShare).div(1e12);\n emit Deposit(msg.sender, _pid, _amount);\n }\n\n // Withdraw LP tokens from MasterChef.\n function withdraw(uint256 _pid, uint256 _amount) public {\n PoolInfo storage pool = poolInfo[_pid];\n UserInfo storage user = userInfo[_pid][msg.sender];\n require(user.amount >= _amount, \"withdraw: not good\");\n updatePool(_pid);\n uint256 pending =\n user.amount.mul(pool.accSushiPerShare).div(1e12).sub(\n user.rewardDebt\n );\n safeSushiTransfer(msg.sender, pending);\n user.amount = user.amount.sub(_amount);\n user.rewardDebt = user.amount.mul(pool.accSushiPerShare).div(1e12);\n pool.lpToken.safeTransfer(address(msg.sender), _amount);\n emit Withdraw(msg.sender, _pid, _amount);\n }\n\n // Withdraw without caring about rewards. EMERGENCY ONLY.\n function emergencyWithdraw(uint256 _pid) public {\n PoolInfo storage pool = poolInfo[_pid];\n UserInfo storage user = userInfo[_pid][msg.sender];\n pool.lpToken.safeTransfer(address(msg.sender), user.amount);\n emit EmergencyWithdraw(msg.sender, _pid, user.amount);\n user.amount = 0;\n user.rewardDebt = 0;\n }\n\n // Safe sushi transfer function, just in case if rounding error causes pool to not have enough SUSHIs.\n function safeSushiTransfer(address _to, uint256 _amount) internal {\n uint256 sushiBal = sushi.balanceOf(address(this));\n if (_amount > sushiBal) {\n sushi.transfer(_to, sushiBal);\n } else {\n sushi.transfer(_to, _amount);\n }\n }\n\n // Update dev address by the previous dev.\n function dev(address _devaddr) public {\n require(msg.sender == devaddr, \"dev: wut?\");\n devaddr = _devaddr;\n }\n\n // Update bonus end block\n function updateBonusEndBlock(uint256 _bonusEndBlock) public onlyOwner {\n bonusEndBlock = _bonusEndBlock;\n }\n}\n"
|
|
},
|
|
"@openzeppelin/contracts/utils/EnumerableSet.sol": {
|
|
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.6.0 <0.8.0;\n\n/**\n * @dev Library for managing\n * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive\n * types.\n *\n * Sets have the following properties:\n *\n * - Elements are added, removed, and checked for existence in constant time\n * (O(1)).\n * - Elements are enumerated in O(n). No guarantees are made on the ordering.\n *\n * ```\n * contract Example {\n * // Add the library methods\n * using EnumerableSet for EnumerableSet.AddressSet;\n *\n * // Declare a set state variable\n * EnumerableSet.AddressSet private mySet;\n * }\n * ```\n *\n * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)\n * and `uint256` (`UintSet`) are supported.\n */\nlibrary EnumerableSet {\n // To implement this library for multiple types with as little code\n // repetition as possible, we write it in terms of a generic Set type with\n // bytes32 values.\n // The Set implementation uses private functions, and user-facing\n // implementations (such as AddressSet) are just wrappers around the\n // underlying Set.\n // This means that we can only create new EnumerableSets for types that fit\n // in bytes32.\n\n struct Set {\n // Storage of set values\n bytes32[] _values;\n\n // Position of the value in the `values` array, plus 1 because index 0\n // means a value is not in the set.\n mapping (bytes32 => uint256) _indexes;\n }\n\n /**\n * @dev Add a value to a set. O(1).\n *\n * Returns true if the value was added to the set, that is if it was not\n * already present.\n */\n function _add(Set storage set, bytes32 value) private returns (bool) {\n if (!_contains(set, value)) {\n set._values.push(value);\n // The value is stored at length-1, but we add 1 to all indexes\n // and use 0 as a sentinel value\n set._indexes[value] = set._values.length;\n return true;\n } else {\n return false;\n }\n }\n\n /**\n * @dev Removes a value from a set. O(1).\n *\n * Returns true if the value was removed from the set, that is if it was\n * present.\n */\n function _remove(Set storage set, bytes32 value) private returns (bool) {\n // We read and store the value's index to prevent multiple reads from the same storage slot\n uint256 valueIndex = set._indexes[value];\n\n if (valueIndex != 0) { // Equivalent to contains(set, value)\n // To delete an element from the _values array in O(1), we swap the element to delete with the last one in\n // the array, and then remove the last element (sometimes called as 'swap and pop').\n // This modifies the order of the array, as noted in {at}.\n\n uint256 toDeleteIndex = valueIndex - 1;\n uint256 lastIndex = set._values.length - 1;\n\n // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs\n // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.\n\n bytes32 lastvalue = set._values[lastIndex];\n\n // Move the last value to the index where the value to delete is\n set._values[toDeleteIndex] = lastvalue;\n // Update the index for the moved value\n set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based\n\n // Delete the slot where the moved value was stored\n set._values.pop();\n\n // Delete the index for the deleted slot\n delete set._indexes[value];\n\n return true;\n } else {\n return false;\n }\n }\n\n /**\n * @dev Returns true if the value is in the set. O(1).\n */\n function _contains(Set storage set, bytes32 value) private view returns (bool) {\n return set._indexes[value] != 0;\n }\n\n /**\n * @dev Returns the number of values on the set. O(1).\n */\n function _length(Set storage set) private view returns (uint256) {\n return set._values.length;\n }\n\n /**\n * @dev Returns the value stored at position `index` in the set. O(1).\n *\n * Note that there are no guarantees on the ordering of values inside the\n * array, and it may change when more values are added or removed.\n *\n * Requirements:\n *\n * - `index` must be strictly less than {length}.\n */\n function _at(Set storage set, uint256 index) private view returns (bytes32) {\n require(set._values.length > index, \"EnumerableSet: index out of bounds\");\n return set._values[index];\n }\n\n // Bytes32Set\n\n struct Bytes32Set {\n Set _inner;\n }\n\n /**\n * @dev Add a value to a set. O(1).\n *\n * Returns true if the value was added to the set, that is if it was not\n * already present.\n */\n function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {\n return _add(set._inner, value);\n }\n\n /**\n * @dev Removes a value from a set. O(1).\n *\n * Returns true if the value was removed from the set, that is if it was\n * present.\n */\n function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {\n return _remove(set._inner, value);\n }\n\n /**\n * @dev Returns true if the value is in the set. O(1).\n */\n function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {\n return _contains(set._inner, value);\n }\n\n /**\n * @dev Returns the number of values in the set. O(1).\n */\n function length(Bytes32Set storage set) internal view returns (uint256) {\n return _length(set._inner);\n }\n\n /**\n * @dev Returns the value stored at position `index` in the set. O(1).\n *\n * Note that there are no guarantees on the ordering of values inside the\n * array, and it may change when more values are added or removed.\n *\n * Requirements:\n *\n * - `index` must be strictly less than {length}.\n */\n function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {\n return _at(set._inner, index);\n }\n\n // AddressSet\n\n struct AddressSet {\n Set _inner;\n }\n\n /**\n * @dev Add a value to a set. O(1).\n *\n * Returns true if the value was added to the set, that is if it was not\n * already present.\n */\n function add(AddressSet storage set, address value) internal returns (bool) {\n return _add(set._inner, bytes32(uint256(uint160(value))));\n }\n\n /**\n * @dev Removes a value from a set. O(1).\n *\n * Returns true if the value was removed from the set, that is if it was\n * present.\n */\n function remove(AddressSet storage set, address value) internal returns (bool) {\n return _remove(set._inner, bytes32(uint256(uint160(value))));\n }\n\n /**\n * @dev Returns true if the value is in the set. O(1).\n */\n function contains(AddressSet storage set, address value) internal view returns (bool) {\n return _contains(set._inner, bytes32(uint256(uint160(value))));\n }\n\n /**\n * @dev Returns the number of values in the set. O(1).\n */\n function length(AddressSet storage set) internal view returns (uint256) {\n return _length(set._inner);\n }\n\n /**\n * @dev Returns the value stored at position `index` in the set. O(1).\n *\n * Note that there are no guarantees on the ordering of values inside the\n * array, and it may change when more values are added or removed.\n *\n * Requirements:\n *\n * - `index` must be strictly less than {length}.\n */\n function at(AddressSet storage set, uint256 index) internal view returns (address) {\n return address(uint160(uint256(_at(set._inner, index))));\n }\n\n\n // UintSet\n\n struct UintSet {\n Set _inner;\n }\n\n /**\n * @dev Add a value to a set. O(1).\n *\n * Returns true if the value was added to the set, that is if it was not\n * already present.\n */\n function add(UintSet storage set, uint256 value) internal returns (bool) {\n return _add(set._inner, bytes32(value));\n }\n\n /**\n * @dev Removes a value from a set. O(1).\n *\n * Returns true if the value was removed from the set, that is if it was\n * present.\n */\n function remove(UintSet storage set, uint256 value) internal returns (bool) {\n return _remove(set._inner, bytes32(value));\n }\n\n /**\n * @dev Returns true if the value is in the set. O(1).\n */\n function contains(UintSet storage set, uint256 value) internal view returns (bool) {\n return _contains(set._inner, bytes32(value));\n }\n\n /**\n * @dev Returns the number of values on the set. O(1).\n */\n function length(UintSet storage set) internal view returns (uint256) {\n return _length(set._inner);\n }\n\n /**\n * @dev Returns the value stored at position `index` in the set. O(1).\n *\n * Note that there are no guarantees on the ordering of values inside the\n * array, and it may change when more values are added or removed.\n *\n * Requirements:\n *\n * - `index` must be strictly less than {length}.\n */\n function at(UintSet storage set, uint256 index) internal view returns (uint256) {\n return uint256(_at(set._inner, index));\n }\n}\n"
|
|
},
|
|
"@openzeppelin/contracts/access/Ownable.sol": {
|
|
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.6.0 <0.8.0;\n\nimport \"../utils/Context.sol\";\n/**\n * @dev Contract module which provides a basic access control mechanism, where\n * there is an account (an owner) that can be granted exclusive access to\n * specific functions.\n *\n * By default, the owner account will be the one that deploys the contract. This\n * can later be changed with {transferOwnership}.\n *\n * This module is used through inheritance. It will make available the modifier\n * `onlyOwner`, which can be applied to your functions to restrict their use to\n * the owner.\n */\nabstract contract Ownable is Context {\n address private _owner;\n\n event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);\n\n /**\n * @dev Initializes the contract setting the deployer as the initial owner.\n */\n constructor () internal {\n address msgSender = _msgSender();\n _owner = msgSender;\n emit OwnershipTransferred(address(0), msgSender);\n }\n\n /**\n * @dev Returns the address of the current owner.\n */\n function owner() public view virtual returns (address) {\n return _owner;\n }\n\n /**\n * @dev Throws if called by any account other than the owner.\n */\n modifier onlyOwner() {\n require(owner() == _msgSender(), \"Ownable: caller is not the owner\");\n _;\n }\n\n /**\n * @dev Leaves the contract without owner. It will not be possible to call\n * `onlyOwner` functions anymore. Can only be called by the current owner.\n *\n * NOTE: Renouncing ownership will leave the contract without an owner,\n * thereby removing any functionality that is only available to the owner.\n */\n function renounceOwnership() public virtual onlyOwner {\n emit OwnershipTransferred(_owner, address(0));\n _owner = address(0);\n }\n\n /**\n * @dev Transfers ownership of the contract to a new account (`newOwner`).\n * Can only be called by the current owner.\n */\n function transferOwnership(address newOwner) public virtual onlyOwner {\n require(newOwner != address(0), \"Ownable: new owner is the zero address\");\n emit OwnershipTransferred(_owner, newOwner);\n _owner = newOwner;\n }\n}\n"
|
|
},
|
|
"contracts/SushiToken.sol": {
|
|
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity 0.6.12;\n\nimport \"@openzeppelin/contracts/token/ERC20/ERC20.sol\";\nimport \"@openzeppelin/contracts/access/Ownable.sol\";\n\n// WARNING: There is a known vuln contained within this contract related to vote delegation, \n// it's NOT recommmended to use this in production. \n\n// SushiToken with Governance.\ncontract SushiToken is ERC20(\"Powswap\", \"POW\"), Ownable {\n /// @notice Creates `_amount` token to `_to`. Must only be called by the owner (MasterChef).\n function mint(address _to, uint256 _amount) public onlyOwner {\n _mint(_to, _amount);\n _moveDelegates(address(0), _delegates[_to], _amount);\n }\n\n // Copied and modified from YAM code:\n // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol\n // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol\n // Which is copied and modified from COMPOUND:\n // https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol\n\n /// @notice A record of each accounts delegate\n mapping (address => address) internal _delegates;\n\n /// @notice A checkpoint for marking number of votes from a given block\n struct Checkpoint {\n uint32 fromBlock;\n uint256 votes;\n }\n\n /// @notice A record of votes checkpoints for each account, by index\n mapping (address => mapping (uint32 => Checkpoint)) public checkpoints;\n\n /// @notice The number of checkpoints for each account\n mapping (address => uint32) public numCheckpoints;\n\n /// @notice The EIP-712 typehash for the contract's domain\n bytes32 public constant DOMAIN_TYPEHASH = keccak256(\"EIP712Domain(string name,uint256 chainId,address verifyingContract)\");\n\n /// @notice The EIP-712 typehash for the delegation struct used by the contract\n bytes32 public constant DELEGATION_TYPEHASH = keccak256(\"Delegation(address delegatee,uint256 nonce,uint256 expiry)\");\n\n /// @notice A record of states for signing / validating signatures\n mapping (address => uint) public nonces;\n\n /// @notice An event thats emitted when an account changes its delegate\n event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);\n\n /// @notice An event thats emitted when a delegate account's vote balance changes\n event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);\n\n /**\n * @notice Delegate votes from `msg.sender` to `delegatee`\n * @param delegator The address to get delegatee for\n */\n function delegates(address delegator)\n external\n view\n returns (address)\n {\n return _delegates[delegator];\n }\n\n /**\n * @notice Delegate votes from `msg.sender` to `delegatee`\n * @param delegatee The address to delegate votes to\n */\n function delegate(address delegatee) external {\n return _delegate(msg.sender, delegatee);\n }\n\n /**\n * @notice Delegates votes from signatory to `delegatee`\n * @param delegatee The address to delegate votes to\n * @param nonce The contract state required to match the signature\n * @param expiry The time at which to expire the signature\n * @param v The recovery byte of the signature\n * @param r Half of the ECDSA signature pair\n * @param s Half of the ECDSA signature pair\n */\n function delegateBySig(\n address delegatee,\n uint nonce,\n uint expiry,\n uint8 v,\n bytes32 r,\n bytes32 s\n )\n external\n {\n bytes32 domainSeparator = keccak256(\n abi.encode(\n DOMAIN_TYPEHASH,\n keccak256(bytes(name())),\n getChainId(),\n address(this)\n )\n );\n\n bytes32 structHash = keccak256(\n abi.encode(\n DELEGATION_TYPEHASH,\n delegatee,\n nonce,\n expiry\n )\n );\n\n bytes32 digest = keccak256(\n abi.encodePacked(\n \"\\x19\\x01\",\n domainSeparator,\n structHash\n )\n );\n\n address signatory = ecrecover(digest, v, r, s);\n require(signatory != address(0), \"SUSHI::delegateBySig: invalid signature\");\n require(nonce == nonces[signatory]++, \"SUSHI::delegateBySig: invalid nonce\");\n require(now <= expiry, \"SUSHI::delegateBySig: signature expired\");\n return _delegate(signatory, delegatee);\n }\n\n /**\n * @notice Gets the current votes balance for `account`\n * @param account The address to get votes balance\n * @return The number of current votes for `account`\n */\n function getCurrentVotes(address account)\n external\n view\n returns (uint256)\n {\n uint32 nCheckpoints = numCheckpoints[account];\n return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;\n }\n\n /**\n * @notice Determine the prior number of votes for an account as of a block number\n * @dev Block number must be a finalized block or else this function will revert to prevent misinformation.\n * @param account The address of the account to check\n * @param blockNumber The block number to get the vote balance at\n * @return The number of votes the account had as of the given block\n */\n function getPriorVotes(address account, uint blockNumber)\n external\n view\n returns (uint256)\n {\n require(blockNumber < block.number, \"SUSHI::getPriorVotes: not yet determined\");\n\n uint32 nCheckpoints = numCheckpoints[account];\n if (nCheckpoints == 0) {\n return 0;\n }\n\n // First check most recent balance\n if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {\n return checkpoints[account][nCheckpoints - 1].votes;\n }\n\n // Next check implicit zero balance\n if (checkpoints[account][0].fromBlock > blockNumber) {\n return 0;\n }\n\n uint32 lower = 0;\n uint32 upper = nCheckpoints - 1;\n while (upper > lower) {\n uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow\n Checkpoint memory cp = checkpoints[account][center];\n if (cp.fromBlock == blockNumber) {\n return cp.votes;\n } else if (cp.fromBlock < blockNumber) {\n lower = center;\n } else {\n upper = center - 1;\n }\n }\n return checkpoints[account][lower].votes;\n }\n\n function _delegate(address delegator, address delegatee)\n internal\n {\n address currentDelegate = _delegates[delegator];\n uint256 delegatorBalance = balanceOf(delegator); // balance of underlying SUSHIs (not scaled);\n _delegates[delegator] = delegatee;\n\n emit DelegateChanged(delegator, currentDelegate, delegatee);\n\n _moveDelegates(currentDelegate, delegatee, delegatorBalance);\n }\n\n function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal {\n if (srcRep != dstRep && amount > 0) {\n if (srcRep != address(0)) {\n // decrease old representative\n uint32 srcRepNum = numCheckpoints[srcRep];\n uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;\n uint256 srcRepNew = srcRepOld.sub(amount);\n _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);\n }\n\n if (dstRep != address(0)) {\n // increase new representative\n uint32 dstRepNum = numCheckpoints[dstRep];\n uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;\n uint256 dstRepNew = dstRepOld.add(amount);\n _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);\n }\n }\n }\n\n function _writeCheckpoint(\n address delegatee,\n uint32 nCheckpoints,\n uint256 oldVotes,\n uint256 newVotes\n )\n internal\n {\n uint32 blockNumber = safe32(block.number, \"SUSHI::_writeCheckpoint: block number exceeds 32 bits\");\n\n if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {\n checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;\n } else {\n checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);\n numCheckpoints[delegatee] = nCheckpoints + 1;\n }\n\n emit DelegateVotesChanged(delegatee, oldVotes, newVotes);\n }\n\n function safe32(uint n, string memory errorMessage) internal pure returns (uint32) {\n require(n < 2**32, errorMessage);\n return uint32(n);\n }\n\n function getChainId() internal pure returns (uint) {\n uint256 chainId;\n assembly { chainId := chainid() }\n return chainId;\n }\n}"
|
|
}
|
|
},
|
|
"settings": {
|
|
"optimizer": {
|
|
"enabled": true,
|
|
"runs": 200
|
|
},
|
|
"outputSelection": {
|
|
"*": {
|
|
"*": [
|
|
"evm.bytecode",
|
|
"evm.deployedBytecode",
|
|
"devdoc",
|
|
"userdoc",
|
|
"metadata",
|
|
"abi"
|
|
]
|
|
}
|
|
},
|
|
"metadata": {
|
|
"useLiteralContent": true
|
|
},
|
|
"libraries": {
|
|
"": {
|
|
"__CACHE_BREAKER__": "0x00000000d41867734bbee4c6863d9255b2b06ac1"
|
|
}
|
|
}
|
|
}
|
|
} |