// Dependency file: @openzeppelin/contracts/utils/Address.sol
// SPDX-License-Identifier: MIT
// pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [// importANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* // importANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// Dependency file: @openzeppelin/contracts/token/ERC20/IERC20.sol
// pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* // importANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// Dependency file: @uniswap/v2-core/contracts/interfaces/IUniswapV2Factory.sol
// pragma solidity >=0.5.0;
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
// Dependency file: @uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router01.sol
// pragma solidity >=0.6.2;
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
// Dependency file: @uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol
// pragma solidity >=0.6.2;
// import '/Users/alexsoong/Source/set-protocol/index-coop-contracts/node_modules/@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router01.sol';
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
// Dependency file: @openzeppelin/contracts/math/Math.sol
// pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
// Dependency file: @openzeppelin/contracts/math/SafeMath.sol
// pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// Dependency file: @openzeppelin/contracts/token/ERC20/SafeERC20.sol
// pragma solidity >=0.6.0 <0.8.0;
// import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
// import "@openzeppelin/contracts/math/SafeMath.sol";
// import "@openzeppelin/contracts/utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// Dependency file: @openzeppelin/contracts/utils/ReentrancyGuard.sol
// pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor () internal {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// Dependency file: contracts/interfaces/ISetToken.sol
// pragma solidity 0.6.10;
pragma experimental "ABIEncoderV2";
// import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* @title ISetToken
* @author Set Protocol
*
* Interface for operating with SetTokens.
*/
interface ISetToken is IERC20 {
/* ============ Enums ============ */
enum ModuleState {
NONE,
PENDING,
INITIALIZED
}
/* ============ Structs ============ */
/**
* The base definition of a SetToken Position
*
* @param component Address of token in the Position
* @param module If not in default state, the address of associated module
* @param unit Each unit is the # of components per 10^18 of a SetToken
* @param positionState Position ENUM. Default is 0; External is 1
* @param data Arbitrary data
*/
struct Position {
address component;
address module;
int256 unit;
uint8 positionState;
bytes data;
}
/**
* A struct that stores a component's cash position details and external positions
* This data structure allows O(1) access to a component's cash position units and
* virtual units.
*
* @param virtualUnit Virtual value of a component's DEFAULT position. Stored as virtual for efficiency
* updating all units at once via the position multiplier. Virtual units are achieved
* by dividing a "real" value by the "positionMultiplier"
* @param componentIndex
* @param externalPositionModules List of external modules attached to each external position. Each module
* maps to an external position
* @param externalPositions Mapping of module => ExternalPosition struct for a given component
*/
struct ComponentPosition {
int256 virtualUnit;
address[] externalPositionModules;
mapping(address => ExternalPosition) externalPositions;
}
/**
* A struct that stores a component's external position details including virtual unit and any
* auxiliary data.
*
* @param virtualUnit Virtual value of a component's EXTERNAL position.
* @param data Arbitrary data
*/
struct ExternalPosition {
int256 virtualUnit;
bytes data;
}
/* ============ Functions ============ */
function addComponent(address _component) external;
function removeComponent(address _component) external;
function editDefaultPositionUnit(address _component, int256 _realUnit) external;
function addExternalPositionModule(address _component, address _positionModule) external;
function removeExternalPositionModule(address _component, address _positionModule) external;
function editExternalPositionUnit(address _component, address _positionModule, int256 _realUnit) external;
function editExternalPositionData(address _component, address _positionModule, bytes calldata _data) external;
function invoke(address _target, uint256 _value, bytes calldata _data) external returns(bytes memory);
function editPositionMultiplier(int256 _newMultiplier) external;
function mint(address _account, uint256 _quantity) external;
function burn(address _account, uint256 _quantity) external;
function lock() external;
function unlock() external;
function addModule(address _module) external;
function removeModule(address _module) external;
function initializeModule() external;
function setManager(address _manager) external;
function manager() external view returns (address);
function moduleStates(address _module) external view returns (ModuleState);
function getModules() external view returns (address[] memory);
function getDefaultPositionRealUnit(address _component) external view returns(int256);
function getExternalPositionRealUnit(address _component, address _positionModule) external view returns(int256);
function getComponents() external view returns(address[] memory);
function getExternalPositionModules(address _component) external view returns(address[] memory);
function getExternalPositionData(address _component, address _positionModule) external view returns(bytes memory);
function isExternalPositionModule(address _component, address _module) external view returns(bool);
function isComponent(address _component) external view returns(bool);
function positionMultiplier() external view returns (int256);
function getPositions() external view returns (Position[] memory);
function getTotalComponentRealUnits(address _component) external view returns(int256);
function isInitializedModule(address _module) external view returns(bool);
function isPendingModule(address _module) external view returns(bool);
function isLocked() external view returns (bool);
}
// Dependency file: contracts/interfaces/IBasicIssuanceModule.sol
/*
Copyright 2020 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// pragma solidity >=0.6.10;
// import { ISetToken } from "contracts/interfaces/ISetToken.sol";
interface IBasicIssuanceModule {
function getRequiredComponentUnitsForIssue(
ISetToken _setToken,
uint256 _quantity
) external returns(address[] memory, uint256[] memory);
function issue(ISetToken _setToken, uint256 _quantity, address _to) external;
function redeem(ISetToken _token, uint256 _quantity, address _to) external;
}
// Dependency file: contracts/interfaces/IController.sol
/*
Copyright 2020 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// pragma solidity 0.6.10;
interface IController {
function addSet(address _setToken) external;
function feeRecipient() external view returns(address);
function getModuleFee(address _module, uint256 _feeType) external view returns(uint256);
function isModule(address _module) external view returns(bool);
function isSet(address _setToken) external view returns(bool);
function isSystemContract(address _contractAddress) external view returns (bool);
function resourceId(uint256 _id) external view returns(address);
}
// Dependency file: contracts/interfaces/IWETH.sol
// pragma solidity >=0.6.10;
interface IWETH {
function deposit() external payable;
function transfer(address to, uint value) external returns (bool);
function withdraw(uint) external;
}
// Dependency file: @openzeppelin/contracts/math/SignedSafeMath.sol
// pragma solidity >=0.6.0 <0.8.0;
/**
* @title SignedSafeMath
* @dev Signed math operations with safety checks that revert on error.
*/
library SignedSafeMath {
int256 constant private _INT256_MIN = -2**255;
/**
* @dev Returns the multiplication of two signed integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(int256 a, int256 b) internal pure returns (int256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
require(!(a == -1 && b == _INT256_MIN), "SignedSafeMath: multiplication overflow");
int256 c = a * b;
require(c / a == b, "SignedSafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two signed integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(int256 a, int256 b) internal pure returns (int256) {
require(b != 0, "SignedSafeMath: division by zero");
require(!(b == -1 && a == _INT256_MIN), "SignedSafeMath: division overflow");
int256 c = a / b;
return c;
}
/**
* @dev Returns the subtraction of two signed integers, reverting on
* overflow.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(int256 a, int256 b) internal pure returns (int256) {
int256 c = a - b;
require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow");
return c;
}
/**
* @dev Returns the addition of two signed integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(int256 a, int256 b) internal pure returns (int256) {
int256 c = a + b;
require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow");
return c;
}
}
// Dependency file: contracts/lib/PreciseUnitMath.sol
/*
Copyright 2020 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// pragma solidity 0.6.10;
// import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
// import { SignedSafeMath } from "@openzeppelin/contracts/math/SignedSafeMath.sol";
/**
* @title PreciseUnitMath
* @author Set Protocol
*
* Arithmetic for fixed-point numbers with 18 decimals of precision. Some functions taken from
* dYdX's BaseMath library.
*
* CHANGELOG:
* - 9/21/20: Added safePower function
*/
library PreciseUnitMath {
using SafeMath for uint256;
using SignedSafeMath for int256;
// The number One in precise units.
uint256 constant internal PRECISE_UNIT = 10 ** 18;
int256 constant internal PRECISE_UNIT_INT = 10 ** 18;
// Max unsigned integer value
uint256 constant internal MAX_UINT_256 = type(uint256).max;
// Max and min signed integer value
int256 constant internal MAX_INT_256 = type(int256).max;
int256 constant internal MIN_INT_256 = type(int256).min;
/**
* @dev Getter function since constants can't be read directly from libraries.
*/
function preciseUnit() internal pure returns (uint256) {
return PRECISE_UNIT;
}
/**
* @dev Getter function since constants can't be read directly from libraries.
*/
function preciseUnitInt() internal pure returns (int256) {
return PRECISE_UNIT_INT;
}
/**
* @dev Getter function since constants can't be read directly from libraries.
*/
function maxUint256() internal pure returns (uint256) {
return MAX_UINT_256;
}
/**
* @dev Getter function since constants can't be read directly from libraries.
*/
function maxInt256() internal pure returns (int256) {
return MAX_INT_256;
}
/**
* @dev Getter function since constants can't be read directly from libraries.
*/
function minInt256() internal pure returns (int256) {
return MIN_INT_256;
}
/**
* @dev Multiplies value a by value b (result is rounded down). It's assumed that the value b is the significand
* of a number with 18 decimals precision.
*/
function preciseMul(uint256 a, uint256 b) internal pure returns (uint256) {
return a.mul(b).div(PRECISE_UNIT);
}
/**
* @dev Multiplies value a by value b (result is rounded towards zero). It's assumed that the value b is the
* significand of a number with 18 decimals precision.
*/
function preciseMul(int256 a, int256 b) internal pure returns (int256) {
return a.mul(b).div(PRECISE_UNIT_INT);
}
/**
* @dev Multiplies value a by value b (result is rounded up). It's assumed that the value b is the significand
* of a number with 18 decimals precision.
*/
function preciseMulCeil(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0 || b == 0) {
return 0;
}
return a.mul(b).sub(1).div(PRECISE_UNIT).add(1);
}
/**
* @dev Divides value a by value b (result is rounded down).
*/
function preciseDiv(uint256 a, uint256 b) internal pure returns (uint256) {
return a.mul(PRECISE_UNIT).div(b);
}
/**
* @dev Divides value a by value b (result is rounded towards 0).
*/
function preciseDiv(int256 a, int256 b) internal pure returns (int256) {
return a.mul(PRECISE_UNIT_INT).div(b);
}
/**
* @dev Divides value a by value b (result is rounded up or away from 0).
*/
function preciseDivCeil(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "Cant divide by 0");
return a > 0 ? a.mul(PRECISE_UNIT).sub(1).div(b).add(1) : 0;
}
/**
* @dev Divides value a by value b (result is rounded down - positive numbers toward 0 and negative away from 0).
*/
function divDown(int256 a, int256 b) internal pure returns (int256) {
require(b != 0, "Cant divide by 0");
require(a != MIN_INT_256 || b != -1, "Invalid input");
int256 result = a.div(b);
if (a ^ b < 0 && a % b != 0) {
result -= 1;
}
return result;
}
/**
* @dev Multiplies value a by value b where rounding is towards the lesser number.
* (positive values are rounded towards zero and negative values are rounded away from 0).
*/
function conservativePreciseMul(int256 a, int256 b) internal pure returns (int256) {
return divDown(a.mul(b), PRECISE_UNIT_INT);
}
/**
* @dev Divides value a by value b where rounding is towards the lesser number.
* (positive values are rounded towards zero and negative values are rounded away from 0).
*/
function conservativePreciseDiv(int256 a, int256 b) internal pure returns (int256) {
return divDown(a.mul(PRECISE_UNIT_INT), b);
}
/**
* @dev Performs the power on a specified value, reverts on overflow.
*/
function safePower(
uint256 a,
uint256 pow
)
internal
pure
returns (uint256)
{
require(a > 0, "Value must be positive");
uint256 result = 1;
for (uint256 i = 0; i < pow; i++){
uint256 previousResult = result;
// Using safemath multiplication prevents overflows
result = previousResult.mul(a);
}
return result;
}
}
// Dependency file: @uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol
// pragma solidity >=0.5.0;
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
// Dependency file: external/contracts/UniSushiV2Library.sol
// pragma solidity >=0.5.0;
// import '/Users/alexsoong/Source/set-protocol/index-coop-contracts/node_modules/@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol';
// import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
library UniSushiV2Library {
using SafeMath for uint;
// returns sorted token addresses, used to handle return values from pairs sorted in this order
function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) {
require(tokenA != tokenB, 'UniswapV2Library: IDENTICAL_ADDRESSES');
(token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
require(token0 != address(0), 'UniswapV2Library: ZERO_ADDRESS');
}
// fetches and sorts the reserves for a pair
function getReserves(address pair, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) {
(address token0,) = sortTokens(tokenA, tokenB);
(uint reserve0, uint reserve1,) = IUniswapV2Pair(pair).getReserves();
(reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
}
// given some amount of an asset and pair reserves, returns an equivalent amount of the other asset
function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) {
require(amountA > 0, 'UniswapV2Library: INSUFFICIENT_AMOUNT');
require(reserveA > 0 && reserveB > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
amountB = amountA.mul(reserveB) / reserveA;
}
// given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) {
require(amountIn > 0, 'UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
uint amountInWithFee = amountIn.mul(997);
uint numerator = amountInWithFee.mul(reserveOut);
uint denominator = reserveIn.mul(1000).add(amountInWithFee);
amountOut = numerator / denominator;
}
// given an output amount of an asset and pair reserves, returns a required input amount of the other asset
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) {
require(amountOut > 0, 'UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
uint numerator = reserveIn.mul(amountOut).mul(1000);
uint denominator = reserveOut.sub(amountOut).mul(997);
amountIn = (numerator / denominator).add(1);
}
// performs chained getAmountOut calculations on any number of pairs
function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) {
require(path.length >= 2, 'UniswapV2Library: INVALID_PATH');
amounts = new uint[](path.length);
amounts[0] = amountIn;
for (uint i; i < path.length - 1; i++) {
(uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]);
amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut);
}
}
// performs chained getAmountIn calculations on any number of pairs
function getAmountsIn(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) {
require(path.length >= 2, 'UniswapV2Library: INVALID_PATH');
amounts = new uint[](path.length);
amounts[amounts.length - 1] = amountOut;
for (uint i = path.length - 1; i > 0; i--) {
(uint reserveIn, uint reserveOut) = getReserves(factory, path[i - 1], path[i]);
amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut);
}
}
}
// Root file: contracts/exchangeIssuance/ExchangeIssuance.sol
/*
Copyright 2021 Index Cooperative
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity 0.6.10;
// import { Address } from "@openzeppelin/contracts/utils/Address.sol";
// import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
// import { IUniswapV2Factory } from "@uniswap/v2-core/contracts/interfaces/IUniswapV2Factory.sol";
// import { IUniswapV2Router02 } from "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol";
// import { Math } from "@openzeppelin/contracts/math/Math.sol";
// import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
// import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
// import { ReentrancyGuard } from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
// import { IBasicIssuanceModule } from "contracts/interfaces/IBasicIssuanceModule.sol";
// import { IController } from "contracts/interfaces/IController.sol";
// import { ISetToken } from "contracts/interfaces/ISetToken.sol";
// import { IWETH } from "contracts/interfaces/IWETH.sol";
// import { PreciseUnitMath } from "contracts/lib/PreciseUnitMath.sol";
// import { UniSushiV2Library } from "external/contracts/UniSushiV2Library.sol";
/**
* @title ExchangeIssuance
* @author Index Coop
*
* Contract for issuing and redeeming any SetToken using ETH or an ERC20 as the paying/receiving currency.
* All swaps are done using the best price found on Uniswap or Sushiswap.
*
*/
contract ExchangeIssuance is ReentrancyGuard {
using Address for address payable;
using SafeMath for uint256;
using PreciseUnitMath for uint256;
using SafeERC20 for IERC20;
using SafeERC20 for ISetToken;
/* ============ Enums ============ */
enum Exchange { Uniswap, Sushiswap, None }
/* ============ Constants ============= */
uint256 constant private MAX_UINT96 = 2**96 - 1;
address constant public ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
/* ============ State Variables ============ */
address public WETH;
IUniswapV2Router02 public uniRouter;
IUniswapV2Router02 public sushiRouter;
address public immutable uniFactory;
address public immutable sushiFactory;
IController public immutable setController;
IBasicIssuanceModule public immutable basicIssuanceModule;
/* ============ Events ============ */
event ExchangeIssue(
address indexed _recipient, // The recipient address of the issued SetTokens
ISetToken indexed _setToken, // The issued SetToken
IERC20 indexed _inputToken, // The address of the input asset(ERC20/ETH) used to issue the SetTokens
uint256 _amountInputToken, // The amount of input tokens used for issuance
uint256 _amountSetIssued // The amount of SetTokens received by the recipient
);
event ExchangeRedeem(
address indexed _recipient, // The recipient address which redeemed the SetTokens
ISetToken indexed _setToken, // The redeemed SetToken
IERC20 indexed _outputToken, // The address of output asset(ERC20/ETH) received by the recipient
uint256 _amountSetRedeemed, // The amount of SetTokens redeemed for output tokens
uint256 _amountOutputToken // The amount of output tokens received by the recipient
);
event Refund(
address indexed _recipient, // The recipient address which redeemed the SetTokens
uint256 _refundAmount // The amount of ETH redunded to the recipient
);
/* ============ Modifiers ============ */
modifier isSetToken(ISetToken _setToken) {
require(setController.isSet(address(_setToken)), "ExchangeIssuance: INVALID SET");
_;
}
/* ============ Constructor ============ */
constructor(
address _weth,
address _uniFactory,
IUniswapV2Router02 _uniRouter,
address _sushiFactory,
IUniswapV2Router02 _sushiRouter,
IController _setController,
IBasicIssuanceModule _basicIssuanceModule
)
public
{
uniFactory = _uniFactory;
uniRouter = _uniRouter;
sushiFactory = _sushiFactory;
sushiRouter = _sushiRouter;
setController = _setController;
basicIssuanceModule = _basicIssuanceModule;
WETH = _weth;
IERC20(WETH).safeApprove(address(uniRouter), PreciseUnitMath.maxUint256());
IERC20(WETH).safeApprove(address(sushiRouter), PreciseUnitMath.maxUint256());
}
/* ============ Public Functions ============ */
/**
* Runs all the necessary approval functions required for a given ERC20 token.
* This function can be called when a new token is added to a SetToken during a
* rebalance.
*
* @param _token Address of the token which needs approval
*/
function approveToken(IERC20 _token) public {
_safeApprove(_token, address(uniRouter), MAX_UINT96);
_safeApprove(_token, address(sushiRouter), MAX_UINT96);
_safeApprove(_token, address(basicIssuanceModule), MAX_UINT96);
}
/* ============ External Functions ============ */
receive() external payable {
// required for weth.withdraw() to work properly
require(msg.sender == WETH, "ExchangeIssuance: Direct deposits not allowed");
}
/**
* Runs all the necessary approval functions required for a list of ERC20 tokens.
*
* @param _tokens Addresses of the tokens which need approval
*/
function approveTokens(IERC20[] calldata _tokens) external {
for (uint256 i = 0; i < _tokens.length; i++) {
approveToken(_tokens[i]);
}
}
/**
* Runs all the necessary approval functions required before issuing
* or redeeming a SetToken. This function need to be called only once before the first time
* this smart contract is used on any particular SetToken.
*
* @param _setToken Address of the SetToken being initialized
*/
function approveSetToken(ISetToken _setToken) isSetToken(_setToken) external {
address[] memory components = _setToken.getComponents();
for (uint256 i = 0; i < components.length; i++) {
// Check that the component does not have external positions
require(
_setToken.getExternalPositionModules(components[i]).length == 0,
"ExchangeIssuance: EXTERNAL_POSITIONS_NOT_ALLOWED"
);
approveToken(IERC20(components[i]));
}
}
/**
* Issues SetTokens for an exact amount of input ERC20 tokens.
* The ERC20 token must be approved by the sender to this contract.
*
* @param _setToken Address of the SetToken being issued
* @param _inputToken Address of input token
* @param _amountInput Amount of the input token / ether to spend
* @param _minSetReceive Minimum amount of SetTokens to receive. Prevents unnecessary slippage.
*
* @return setTokenAmount Amount of SetTokens issued to the caller
*/
function issueSetForExactToken(
ISetToken _setToken,
IERC20 _inputToken,
uint256 _amountInput,
uint256 _minSetReceive
)
isSetToken(_setToken)
external
nonReentrant
returns (uint256)
{
require(_amountInput > 0, "ExchangeIssuance: INVALID INPUTS");
_inputToken.safeTransferFrom(msg.sender, address(this), _amountInput);
uint256 amountEth = address(_inputToken) == WETH
? _amountInput
: _swapTokenForWETH(_inputToken, _amountInput);
uint256 setTokenAmount = _issueSetForExactWETH(_setToken, _minSetReceive, amountEth);
emit ExchangeIssue(msg.sender, _setToken, _inputToken, _amountInput, setTokenAmount);
return setTokenAmount;
}
/**
* Issues SetTokens for an exact amount of input ether.
*
* @param _setToken Address of the SetToken to be issued
* @param _minSetReceive Minimum amount of SetTokens to receive. Prevents unnecessary slippage.
*
* @return setTokenAmount Amount of SetTokens issued to the caller
*/
function issueSetForExactETH(
ISetToken _setToken,
uint256 _minSetReceive
)
isSetToken(_setToken)
external
payable
nonReentrant
returns(uint256)
{
require(msg.value > 0, "ExchangeIssuance: INVALID INPUTS");
IWETH(WETH).deposit{value: msg.value}();
uint256 setTokenAmount = _issueSetForExactWETH(_setToken, _minSetReceive, msg.value);
emit ExchangeIssue(msg.sender, _setToken, IERC20(ETH_ADDRESS), msg.value, setTokenAmount);
return setTokenAmount;
}
/**
* Issues an exact amount of SetTokens for given amount of input ERC20 tokens.
* The excess amount of tokens is returned in an equivalent amount of ether.
*
* @param _setToken Address of the SetToken to be issued
* @param _inputToken Address of the input token
* @param _amountSetToken Amount of SetTokens to issue
* @param _maxAmountInputToken Maximum amount of input tokens to be used to issue SetTokens. The unused
* input tokens are returned as ether.
*
* @return amountEthReturn Amount of ether returned to the caller
*/
function issueExactSetFromToken(
ISetToken _setToken,
IERC20 _inputToken,
uint256 _amountSetToken,
uint256 _maxAmountInputToken
)
isSetToken(_setToken)
external
nonReentrant
returns (uint256)
{
require(_amountSetToken > 0 && _maxAmountInputToken > 0, "ExchangeIssuance: INVALID INPUTS");
_inputToken.safeTransferFrom(msg.sender, address(this), _maxAmountInputToken);
uint256 initETHAmount = address(_inputToken) == WETH
? _maxAmountInputToken
: _swapTokenForWETH(_inputToken, _maxAmountInputToken);
uint256 amountEthSpent = _issueExactSetFromWETH(_setToken, _amountSetToken, initETHAmount);
uint256 amountEthReturn = initETHAmount.sub(amountEthSpent);
if (amountEthReturn > 0) {
IWETH(WETH).withdraw(amountEthReturn);
(payable(msg.sender)).sendValue(amountEthReturn);
}
emit Refund(msg.sender, amountEthReturn);
emit ExchangeIssue(msg.sender, _setToken, _inputToken, _maxAmountInputToken, _amountSetToken);
return amountEthReturn;
}
/**
* Issues an exact amount of SetTokens using a given amount of ether.
* The excess ether is returned back.
*
* @param _setToken Address of the SetToken being issued
* @param _amountSetToken Amount of SetTokens to issue
*
* @return amountEthReturn Amount of ether returned to the caller
*/
function issueExactSetFromETH(
ISetToken _setToken,
uint256 _amountSetToken
)
isSetToken(_setToken)
external
payable
nonReentrant
returns (uint256)
{
require(msg.value > 0 && _amountSetToken > 0, "ExchangeIssuance: INVALID INPUTS");
IWETH(WETH).deposit{value: msg.value}();
uint256 amountEth = _issueExactSetFromWETH(_setToken, _amountSetToken, msg.value);
uint256 amountEthReturn = msg.value.sub(amountEth);
if (amountEthReturn > 0) {
IWETH(WETH).withdraw(amountEthReturn);
(payable(msg.sender)).sendValue(amountEthReturn);
}
emit Refund(msg.sender, amountEthReturn);
emit ExchangeIssue(msg.sender, _setToken, IERC20(ETH_ADDRESS), amountEth, _amountSetToken);
return amountEthReturn;
}
/**
* Redeems an exact amount of SetTokens for an ERC20 token.
* The SetToken must be approved by the sender to this contract.
*
* @param _setToken Address of the SetToken being redeemed
* @param _outputToken Address of output token
* @param _amountSetToken Amount SetTokens to redeem
* @param _minOutputReceive Minimum amount of output token to receive
*
* @return outputAmount Amount of output tokens sent to the caller
*/
function redeemExactSetForToken(
ISetToken _setToken,
IERC20 _outputToken,
uint256 _amountSetToken,
uint256 _minOutputReceive
)
isSetToken(_setToken)
external
nonReentrant
returns (uint256)
{
require(_amountSetToken > 0, "ExchangeIssuance: INVALID INPUTS");
address[] memory components = _setToken.getComponents();
(
uint256 totalEth,
uint256[] memory amountComponents,
Exchange[] memory exchanges
) = _getAmountETHForRedemption(_setToken, components, _amountSetToken);
uint256 outputAmount;
if (address(_outputToken) == WETH) {
require(totalEth > _minOutputReceive, "ExchangeIssuance: INSUFFICIENT_OUTPUT_AMOUNT");
_redeemExactSet(_setToken, _amountSetToken);
outputAmount = _liquidateComponentsForWETH(components, amountComponents, exchanges);
} else {
(uint256 totalOutput, Exchange outTokenExchange, ) = _getMaxTokenForExactToken(totalEth, address(WETH), address(_outputToken));
require(totalOutput > _minOutputReceive, "ExchangeIssuance: INSUFFICIENT_OUTPUT_AMOUNT");
_redeemExactSet(_setToken, _amountSetToken);
uint256 outputEth = _liquidateComponentsForWETH(components, amountComponents, exchanges);
outputAmount = _swapExactTokensForTokens(outTokenExchange, WETH, address(_outputToken), outputEth);
}
_outputToken.safeTransfer(msg.sender, outputAmount);
emit ExchangeRedeem(msg.sender, _setToken, _outputToken, _amountSetToken, outputAmount);
return outputAmount;
}
/**
* Redeems an exact amount of SetTokens for ETH.
* The SetToken must be approved by the sender to this contract.
*
* @param _setToken Address of the SetToken to be redeemed
* @param _amountSetToken Amount of SetTokens to redeem
* @param _minEthOut Minimum amount of ETH to receive
*
* @return amountEthOut Amount of ether sent to the caller
*/
function redeemExactSetForETH(
ISetToken _setToken,
uint256 _amountSetToken,
uint256 _minEthOut
)
isSetToken(_setToken)
external
nonReentrant
returns (uint256)
{
require(_amountSetToken > 0, "ExchangeIssuance: INVALID INPUTS");
address[] memory components = _setToken.getComponents();
(
uint256 totalEth,
uint256[] memory amountComponents,
Exchange[] memory exchanges
) = _getAmountETHForRedemption(_setToken, components, _amountSetToken);
require(totalEth > _minEthOut, "ExchangeIssuance: INSUFFICIENT_OUTPUT_AMOUNT");
_redeemExactSet(_setToken, _amountSetToken);
uint256 amountEthOut = _liquidateComponentsForWETH(components, amountComponents, exchanges);
IWETH(WETH).withdraw(amountEthOut);
(payable(msg.sender)).sendValue(amountEthOut);
emit ExchangeRedeem(msg.sender, _setToken, IERC20(ETH_ADDRESS), _amountSetToken, amountEthOut);
return amountEthOut;
}
/**
* Returns an estimated amount of SetToken that can be issued given an amount of input ERC20 token.
*
* @param _setToken Address of the SetToken being issued
* @param _amountInput Amount of the input token to spend
* @param _inputToken Address of input token.
*
* @return Estimated amount of SetTokens that will be received
*/
function getEstimatedIssueSetAmount(
ISetToken _setToken,
IERC20 _inputToken,
uint256 _amountInput
)
isSetToken(_setToken)
external
view
returns (uint256)
{
require(_amountInput > 0, "ExchangeIssuance: INVALID INPUTS");
uint256 amountEth;
if (address(_inputToken) != WETH) {
// get max amount of WETH for the `_amountInput` amount of input tokens
(amountEth, , ) = _getMaxTokenForExactToken(_amountInput, address(_inputToken), WETH);
} else {
amountEth = _amountInput;
}
address[] memory components = _setToken.getComponents();
(uint256 setIssueAmount, , ) = _getSetIssueAmountForETH(_setToken, components, amountEth);
return setIssueAmount;
}
/**
* Returns the amount of input ERC20 tokens required to issue an exact amount of SetTokens.
*
* @param _setToken Address of the SetToken being issued
* @param _amountSetToken Amount of SetTokens to issue
*
* @return Amount of tokens needed to issue specified amount of SetTokens
*/
function getAmountInToIssueExactSet(
ISetToken _setToken,
IERC20 _inputToken,
uint256 _amountSetToken
)
isSetToken(_setToken)
external
view
returns(uint256)
{
require(_amountSetToken > 0, "ExchangeIssuance: INVALID INPUTS");
address[] memory components = _setToken.getComponents();
(uint256 totalEth, , , , ) = _getAmountETHForIssuance(_setToken, components, _amountSetToken);
if (address(_inputToken) == WETH) {
return totalEth;
}
(uint256 tokenAmount, , ) = _getMinTokenForExactToken(totalEth, address(_inputToken), address(WETH));
return tokenAmount;
}
/**
* Returns amount of output ERC20 tokens received upon redeeming a given amount of SetToken.
*
* @param _setToken Address of SetToken to be redeemed
* @param _amountSetToken Amount of SetToken to be redeemed
* @param _outputToken Address of output token
*
* @return Estimated amount of ether/erc20 that will be received
*/
function getAmountOutOnRedeemSet(
ISetToken _setToken,
address _outputToken,
uint256 _amountSetToken
)
isSetToken(_setToken)
external
view
returns (uint256)
{
require(_amountSetToken > 0, "ExchangeIssuance: INVALID INPUTS");
address[] memory components = _setToken.getComponents();
(uint256 totalEth, , ) = _getAmountETHForRedemption(_setToken, components, _amountSetToken);
if (_outputToken == WETH) {
return totalEth;
}
// get maximum amount of tokens for totalEth amount of ETH
(uint256 tokenAmount, , ) = _getMaxTokenForExactToken(totalEth, WETH, _outputToken);
return tokenAmount;
}
/* ============ Internal Functions ============ */
/**
* Sets a max approval limit for an ERC20 token, provided the current allowance
* is less than the required allownce.
*
* @param _token Token to approve
* @param _spender Spender address to approve
*/
function _safeApprove(IERC20 _token, address _spender, uint256 _requiredAllowance) internal {
uint256 allowance = _token.allowance(address(this), _spender);
if (allowance < _requiredAllowance) {
_token.safeIncreaseAllowance(_spender, MAX_UINT96 - allowance);
}
}
/**
* Issues SetTokens for an exact amount of input WETH.
*
* @param _setToken Address of the SetToken being issued
* @param _minSetReceive Minimum amount of index to receive
* @param _totalEthAmount Total amount of WETH to be used to purchase the SetToken components
*
* @return setTokenAmount Amount of SetTokens issued
*/
function _issueSetForExactWETH(ISetToken _setToken, uint256 _minSetReceive, uint256 _totalEthAmount) internal returns (uint256) {
address[] memory components = _setToken.getComponents();
(
uint256 setIssueAmount,
uint256[] memory amountEthIn,
Exchange[] memory exchanges
) = _getSetIssueAmountForETH(_setToken, components, _totalEthAmount);
require(setIssueAmount > _minSetReceive, "ExchangeIssuance: INSUFFICIENT_OUTPUT_AMOUNT");
for (uint256 i = 0; i < components.length; i++) {
_swapExactTokensForTokens(exchanges[i], WETH, components[i], amountEthIn[i]);
}
basicIssuanceModule.issue(_setToken, setIssueAmount, msg.sender);
return setIssueAmount;
}
/**
* Issues an exact amount of SetTokens using WETH.
* Acquires SetToken components at the best price accross uniswap and sushiswap.
* Uses the acquired components to issue the SetTokens.
*
* @param _setToken Address of the SetToken being issued
* @param _amountSetToken Amount of SetTokens to be issued
* @param _maxEther Max amount of ether that can be used to acquire the SetToken components
*
* @return totalEth Total amount of ether used to acquire the SetToken components
*/
function _issueExactSetFromWETH(ISetToken _setToken, uint256 _amountSetToken, uint256 _maxEther) internal returns (uint256) {
address[] memory components = _setToken.getComponents();
(
uint256 sumEth,
,
Exchange[] memory exchanges,
uint256[] memory amountComponents,
) = _getAmountETHForIssuance(_setToken, components, _amountSetToken);
require(sumEth <= _maxEther, "ExchangeIssuance: INSUFFICIENT_INPUT_AMOUNT");
uint256 totalEth = 0;
for (uint256 i = 0; i < components.length; i++) {
uint256 amountEth = _swapTokensForExactTokens(exchanges[i], WETH, components[i], amountComponents[i]);
totalEth = totalEth.add(amountEth);
}
basicIssuanceModule.issue(_setToken, _amountSetToken, msg.sender);
return totalEth;
}
/**
* Redeems a given amount of SetToken.
*
* @param _setToken Address of the SetToken to be redeemed
* @param _amount Amount of SetToken to be redeemed
*/
function _redeemExactSet(ISetToken _setToken, uint256 _amount) internal returns (uint256) {
_setToken.safeTransferFrom(msg.sender, address(this), _amount);
basicIssuanceModule.redeem(_setToken, _amount, address(this));
}
/**
* Liquidates a given list of SetToken components for WETH.
*
* @param _components An array containing the address of SetToken components
* @param _amountComponents An array containing the amount of each SetToken component
* @param _exchanges An array containing the exchange on which to liquidate the SetToken component
*
* @return Total amount of WETH received after liquidating all SetToken components
*/
function _liquidateComponentsForWETH(address[] memory _components, uint256[] memory _amountComponents, Exchange[] memory _exchanges)
internal
returns (uint256)
{
uint256 sumEth = 0;
for (uint256 i = 0; i < _components.length; i++) {
sumEth = _exchanges[i] == Exchange.None
? sumEth.add(_amountComponents[i])
: sumEth.add(_swapExactTokensForTokens(_exchanges[i], _components[i], WETH, _amountComponents[i]));
}
return sumEth;
}
/**
* Gets the total amount of ether required for purchasing each component in a SetToken,
* to enable the issuance of a given amount of SetTokens.
*
* @param _setToken Address of the SetToken to be issued
* @param _components An array containing the addresses of the SetToken components
* @param _amountSetToken Amount of SetToken to be issued
*
* @return sumEth The total amount of Ether reuired to issue the set
* @return amountEthIn An array containing the amount of ether to purchase each component of the SetToken
* @return exchanges An array containing the exchange on which to perform the purchase
* @return amountComponents An array containing the amount of each SetToken component required for issuing the given
* amount of SetToken
* @return pairAddresses An array containing the pair addresses of ETH/component exchange pool
*/
function _getAmountETHForIssuance(ISetToken _setToken, address[] memory _components, uint256 _amountSetToken)
internal
view
returns (
uint256 sumEth,
uint256[] memory amountEthIn,
Exchange[] memory exchanges,
uint256[] memory amountComponents,
address[] memory pairAddresses
)
{
sumEth = 0;
amountEthIn = new uint256[](_components.length);
amountComponents = new uint256[](_components.length);
exchanges = new Exchange[](_components.length);
pairAddresses = new address[](_components.length);
for (uint256 i = 0; i < _components.length; i++) {
// Check that the component does not have external positions
require(
_setToken.getExternalPositionModules(_components[i]).length == 0,
"ExchangeIssuance: EXTERNAL_POSITIONS_NOT_ALLOWED"
);
// Get minimum amount of ETH to be spent to acquire the required amount of SetToken component
uint256 unit = uint256(_setToken.getDefaultPositionRealUnit(_components[i]));
amountComponents[i] = uint256(unit).preciseMulCeil(_amountSetToken);
(amountEthIn[i], exchanges[i], pairAddresses[i]) = _getMinTokenForExactToken(amountComponents[i], WETH, _components[i]);
sumEth = sumEth.add(amountEthIn[i]);
}
return (sumEth, amountEthIn, exchanges, amountComponents, pairAddresses);
}
/**
* Gets the total amount of ether returned from liquidating each component in a SetToken.
*
* @param _setToken Address of the SetToken to be redeemed
* @param _components An array containing the addresses of the SetToken components
* @param _amountSetToken Amount of SetToken to be redeemed
*
* @return sumEth The total amount of Ether that would be obtained from liquidating the SetTokens
* @return amountComponents An array containing the amount of SetToken component to be liquidated
* @return exchanges An array containing the exchange on which to liquidate the SetToken components
*/
function _getAmountETHForRedemption(ISetToken _setToken, address[] memory _components, uint256 _amountSetToken)
internal
view
returns (uint256, uint256[] memory, Exchange[] memory)
{
uint256 sumEth = 0;
uint256 amountEth = 0;
uint256[] memory amountComponents = new uint256[](_components.length);
Exchange[] memory exchanges = new Exchange[](_components.length);
for (uint256 i = 0; i < _components.length; i++) {
// Check that the component does not have external positions
require(
_setToken.getExternalPositionModules(_components[i]).length == 0,
"ExchangeIssuance: EXTERNAL_POSITIONS_NOT_ALLOWED"
);
uint256 unit = uint256(_setToken.getDefaultPositionRealUnit(_components[i]));
amountComponents[i] = unit.preciseMul(_amountSetToken);
// get maximum amount of ETH received for a given amount of SetToken component
(amountEth, exchanges[i], ) = _getMaxTokenForExactToken(amountComponents[i], _components[i], WETH);
sumEth = sumEth.add(amountEth);
}
return (sumEth, amountComponents, exchanges);
}
/**
* Returns an estimated amount of SetToken that can be issued given an amount of input ERC20 token.
*
* @param _setToken Address of the SetToken to be issued
* @param _components An array containing the addresses of the SetToken components
* @param _amountEth Total amount of ether available for the purchase of SetToken components
*
* @return setIssueAmount The max amount of SetTokens that can be issued
* @return amountEthIn An array containing the amount ether required to purchase each SetToken component
* @return exchanges An array containing the exchange on which to purchase the SetToken components
*/
function _getSetIssueAmountForETH(ISetToken _setToken, address[] memory _components, uint256 _amountEth)
internal
view
returns (uint256 setIssueAmount, uint256[] memory amountEthIn, Exchange[] memory exchanges)
{
uint256 sumEth;
uint256[] memory unitAmountEthIn;
uint256[] memory unitAmountComponents;
address[] memory pairAddresses;
(
sumEth,
unitAmountEthIn,
exchanges,
unitAmountComponents,
pairAddresses
) = _getAmountETHForIssuance(_setToken, _components, PreciseUnitMath.preciseUnit());
setIssueAmount = PreciseUnitMath.maxUint256();
amountEthIn = new uint256[](_components.length);
for (uint256 i = 0; i < _components.length; i++) {
amountEthIn[i] = unitAmountEthIn[i].mul(_amountEth).div(sumEth);
uint256 amountComponent;
if (exchanges[i] == Exchange.None) {
amountComponent = amountEthIn[i];
} else {
(uint256 reserveIn, uint256 reserveOut) = UniSushiV2Library.getReserves(pairAddresses[i], WETH, _components[i]);
amountComponent = UniSushiV2Library.getAmountOut(amountEthIn[i], reserveIn, reserveOut);
}
setIssueAmount = Math.min(amountComponent.preciseDiv(unitAmountComponents[i]), setIssueAmount);
}
return (setIssueAmount, amountEthIn, exchanges);
}
/**
* Swaps a given amount of an ERC20 token for WETH for the best price on Uniswap/Sushiswap.
*
* @param _token Address of the ERC20 token to be swapped for WETH
* @param _amount Amount of ERC20 token to be swapped
*
* @return Amount of WETH received after the swap
*/
function _swapTokenForWETH(IERC20 _token, uint256 _amount) internal returns (uint256) {
(, Exchange exchange, ) = _getMaxTokenForExactToken(_amount, address(_token), WETH);
IUniswapV2Router02 router = _getRouter(exchange);
_safeApprove(_token, address(router), _amount);
return _swapExactTokensForTokens(exchange, address(_token), WETH, _amount);
}
/**
* Swap exact tokens for another token on a given DEX.
*
* @param _exchange The exchange on which to peform the swap
* @param _tokenIn The address of the input token
* @param _tokenOut The address of the output token
* @param _amountIn The amount of input token to be spent
*
* @return The amount of output tokens
*/
function _swapExactTokensForTokens(Exchange _exchange, address _tokenIn, address _tokenOut, uint256 _amountIn) internal returns (uint256) {
if (_tokenIn == _tokenOut) {
return _amountIn;
}
address[] memory path = new address[](2);
path[0] = _tokenIn;
path[1] = _tokenOut;
return _getRouter(_exchange).swapExactTokensForTokens(_amountIn, 0, path, address(this), block.timestamp)[1];
}
/**
* Swap tokens for exact amount of output tokens on a given DEX.
*
* @param _exchange The exchange on which to peform the swap
* @param _tokenIn The address of the input token
* @param _tokenOut The address of the output token
* @param _amountOut The amount of output token required
*
* @return The amount of input tokens spent
*/
function _swapTokensForExactTokens(Exchange _exchange, address _tokenIn, address _tokenOut, uint256 _amountOut) internal returns (uint256) {
if (_tokenIn == _tokenOut) {
return _amountOut;
}
address[] memory path = new address[](2);
path[0] = _tokenIn;
path[1] = _tokenOut;
return _getRouter(_exchange).swapTokensForExactTokens(_amountOut, PreciseUnitMath.maxUint256(), path, address(this), block.timestamp)[0];
}
/**
* Compares the amount of token required for an exact amount of another token across both exchanges,
* and returns the min amount.
*
* @param _amountOut The amount of output token
* @param _tokenA The address of tokenA
* @param _tokenB The address of tokenB
*
* @return The min amount of tokenA required across both exchanges
* @return The Exchange on which minimum amount of tokenA is required
* @return The pair address of the uniswap/sushiswap pool containing _tokenA and _tokenB
*/
function _getMinTokenForExactToken(uint256 _amountOut, address _tokenA, address _tokenB) internal view returns (uint256, Exchange, address) {
if (_tokenA == _tokenB) {
return (_amountOut, Exchange.None, ETH_ADDRESS);
}
uint256 maxIn = PreciseUnitMath.maxUint256() ;
uint256 uniTokenIn = maxIn;
uint256 sushiTokenIn = maxIn;
address uniswapPair = _getPair(uniFactory, _tokenA, _tokenB);
if (uniswapPair != address(0)) {
(uint256 reserveIn, uint256 reserveOut) = UniSushiV2Library.getReserves(uniswapPair, _tokenA, _tokenB);
// Prevent subtraction overflow by making sure pool reserves are greater than swap amount
if (reserveOut > _amountOut) {
uniTokenIn = UniSushiV2Library.getAmountIn(_amountOut, reserveIn, reserveOut);
}
}
address sushiswapPair = _getPair(sushiFactory, _tokenA, _tokenB);
if (sushiswapPair != address(0)) {
(uint256 reserveIn, uint256 reserveOut) = UniSushiV2Library.getReserves(sushiswapPair, _tokenA, _tokenB);
// Prevent subtraction overflow by making sure pool reserves are greater than swap amount
if (reserveOut > _amountOut) {
sushiTokenIn = UniSushiV2Library.getAmountIn(_amountOut, reserveIn, reserveOut);
}
}
// Fails if both the values are maxIn
require(!(uniTokenIn == maxIn && sushiTokenIn == maxIn), "ExchangeIssuance: ILLIQUID_SET_COMPONENT");
return (uniTokenIn <= sushiTokenIn) ? (uniTokenIn, Exchange.Uniswap, uniswapPair) : (sushiTokenIn, Exchange.Sushiswap, sushiswapPair);
}
/**
* Compares the amount of token received for an exact amount of another token across both exchanges,
* and returns the max amount.
*
* @param _amountIn The amount of input token
* @param _tokenA The address of tokenA
* @param _tokenB The address of tokenB
*
* @return The max amount of tokens that can be received across both exchanges
* @return The Exchange on which maximum amount of token can be received
* @return The pair address of the uniswap/sushiswap pool containing _tokenA and _tokenB
*/
function _getMaxTokenForExactToken(uint256 _amountIn, address _tokenA, address _tokenB) internal view returns (uint256, Exchange, address) {
if (_tokenA == _tokenB) {
return (_amountIn, Exchange.None, ETH_ADDRESS);
}
uint256 uniTokenOut = 0;
uint256 sushiTokenOut = 0;
address uniswapPair = _getPair(uniFactory, _tokenA, _tokenB);
if(uniswapPair != address(0)) {
(uint256 reserveIn, uint256 reserveOut) = UniSushiV2Library.getReserves(uniswapPair, _tokenA, _tokenB);
uniTokenOut = UniSushiV2Library.getAmountOut(_amountIn, reserveIn, reserveOut);
}
address sushiswapPair = _getPair(sushiFactory, _tokenA, _tokenB);
if(sushiswapPair != address(0)) {
(uint256 reserveIn, uint256 reserveOut) = UniSushiV2Library.getReserves(sushiswapPair, _tokenA, _tokenB);
sushiTokenOut = UniSushiV2Library.getAmountOut(_amountIn, reserveIn, reserveOut);
}
// Fails if both the values are 0
require(!(uniTokenOut == 0 && sushiTokenOut == 0), "ExchangeIssuance: ILLIQUID_SET_COMPONENT");
return (uniTokenOut >= sushiTokenOut) ? (uniTokenOut, Exchange.Uniswap, uniswapPair) : (sushiTokenOut, Exchange.Sushiswap, sushiswapPair);
}
/**
* Returns the pair address for on a given DEX.
*
* @param _factory The factory to address
* @param _tokenA The address of tokenA
* @param _tokenB The address of tokenB
*
* @return The pair address (Note: address(0) is returned by default if the pair is not available on that DEX)
*/
function _getPair(address _factory, address _tokenA, address _tokenB) internal view returns (address) {
return IUniswapV2Factory(_factory).getPair(_tokenA, _tokenB);
}
/**
* Returns the router address of a given exchange.
*
* @param _exchange The Exchange whose router address is needed
*
* @return IUniswapV2Router02 router of the given exchange
*/
function _getRouter(Exchange _exchange) internal view returns(IUniswapV2Router02) {
return (_exchange == Exchange.Uniswap) ? uniRouter : sushiRouter;
}
}
{
"compilationTarget": {
"ExchangeIssuance.sol": "ExchangeIssuance"
},
"evmVersion": "istanbul",
"libraries": {},
"metadata": {
"bytecodeHash": "ipfs"
},
"optimizer": {
"enabled": true,
"runs": 200
},
"remappings": []
}
[{"inputs":[{"internalType":"address","name":"_weth","type":"address"},{"internalType":"address","name":"_uniFactory","type":"address"},{"internalType":"contract IUniswapV2Router02","name":"_uniRouter","type":"address"},{"internalType":"address","name":"_sushiFactory","type":"address"},{"internalType":"contract IUniswapV2Router02","name":"_sushiRouter","type":"address"},{"internalType":"contract IController","name":"_setController","type":"address"},{"internalType":"contract IBasicIssuanceModule","name":"_basicIssuanceModule","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"_recipient","type":"address"},{"indexed":true,"internalType":"contract ISetToken","name":"_setToken","type":"address"},{"indexed":true,"internalType":"contract IERC20","name":"_inputToken","type":"address"},{"indexed":false,"internalType":"uint256","name":"_amountInputToken","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"_amountSetIssued","type":"uint256"}],"name":"ExchangeIssue","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"_recipient","type":"address"},{"indexed":true,"internalType":"contract ISetToken","name":"_setToken","type":"address"},{"indexed":true,"internalType":"contract IERC20","name":"_outputToken","type":"address"},{"indexed":false,"internalType":"uint256","name":"_amountSetRedeemed","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"_amountOutputToken","type":"uint256"}],"name":"ExchangeRedeem","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"_recipient","type":"address"},{"indexed":false,"internalType":"uint256","name":"_refundAmount","type":"uint256"}],"name":"Refund","type":"event"},{"inputs":[],"name":"ETH_ADDRESS","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"WETH","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"contract ISetToken","name":"_setToken","type":"address"}],"name":"approveSetToken","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"contract IERC20","name":"_token","type":"address"}],"name":"approveToken","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"contract IERC20[]","name":"_tokens","type":"address[]"}],"name":"approveTokens","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"basicIssuanceModule","outputs":[{"internalType":"contract IBasicIssuanceModule","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"contract ISetToken","name":"_setToken","type":"address"},{"internalType":"contract IERC20","name":"_inputToken","type":"address"},{"internalType":"uint256","name":"_amountSetToken","type":"uint256"}],"name":"getAmountInToIssueExactSet","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"contract ISetToken","name":"_setToken","type":"address"},{"internalType":"address","name":"_outputToken","type":"address"},{"internalType":"uint256","name":"_amountSetToken","type":"uint256"}],"name":"getAmountOutOnRedeemSet","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"contract ISetToken","name":"_setToken","type":"address"},{"internalType":"contract IERC20","name":"_inputToken","type":"address"},{"internalType":"uint256","name":"_amountInput","type":"uint256"}],"name":"getEstimatedIssueSetAmount","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"contract ISetToken","name":"_setToken","type":"address"},{"internalType":"uint256","name":"_amountSetToken","type":"uint256"}],"name":"issueExactSetFromETH","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"contract ISetToken","name":"_setToken","type":"address"},{"internalType":"contract IERC20","name":"_inputToken","type":"address"},{"internalType":"uint256","name":"_amountSetToken","type":"uint256"},{"internalType":"uint256","name":"_maxAmountInputToken","type":"uint256"}],"name":"issueExactSetFromToken","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"contract ISetToken","name":"_setToken","type":"address"},{"internalType":"uint256","name":"_minSetReceive","type":"uint256"}],"name":"issueSetForExactETH","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"contract ISetToken","name":"_setToken","type":"address"},{"internalType":"contract IERC20","name":"_inputToken","type":"address"},{"internalType":"uint256","name":"_amountInput","type":"uint256"},{"internalType":"uint256","name":"_minSetReceive","type":"uint256"}],"name":"issueSetForExactToken","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"contract ISetToken","name":"_setToken","type":"address"},{"internalType":"uint256","name":"_amountSetToken","type":"uint256"},{"internalType":"uint256","name":"_minEthOut","type":"uint256"}],"name":"redeemExactSetForETH","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"contract ISetToken","name":"_setToken","type":"address"},{"internalType":"contract IERC20","name":"_outputToken","type":"address"},{"internalType":"uint256","name":"_amountSetToken","type":"uint256"},{"internalType":"uint256","name":"_minOutputReceive","type":"uint256"}],"name":"redeemExactSetForToken","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"setController","outputs":[{"internalType":"contract IController","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"sushiFactory","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"sushiRouter","outputs":[{"internalType":"contract IUniswapV2Router02","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"uniFactory","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"uniRouter","outputs":[{"internalType":"contract IUniswapV2Router02","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"stateMutability":"payable","type":"receive"}]