-
Notifications
You must be signed in to change notification settings - Fork 107
Add TradeSplitter #99
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 32 commits
Commits
Show all changes
44 commits
Select commit
Hold shift + click to select a range
2d80b9b
add _getUniSplit function
ncitron 754f7ec
add swapping
ncitron c78f5c4
only rever when total output < min output
ncitron 48ac58b
use better math for split
ncitron c483e20
add tests
ncitron 1561c74
rename contracts and functions to be inline with spec
ncitron c58ff34
add multi hop support
ncitron 88b2218
add tradeExactOutput
ncitron 682e782
clean up imports
ncitron e72ff11
shorten name
ncitron 8f2c762
add javadocs
ncitron e762696
add getQuote function
ncitron 613d507
clean up ratio calculation
ncitron 70dc237
remove hardhat console
ncitron aea65ac
add TradeSplitterExchangeAdapter
ncitron 7b6ae5a
fix typo causing tests to break
ncitron 443caea
add TradeSplitterIndexExchangeAdapter
ncitron d30e838
improve coverage
ncitron 2c6c425
increase coverage
ncitron 1eaae6f
refactor
ncitron 3331e08
remove redundant if in getQuote
ncitron cca52e3
improve reverts
ncitron be37f79
improve coverage
ncitron 3743225
move TradeSplitter into products
ncitron 82da6c9
add TradeSplitterExchangeAdapter integration test
ncitron 012ed03
split getQuote into two functions for exact input/output
ncitron 07b037d
add TradeSplitter GIM integration tests
ncitron dbb1638
Merge branch 'master' into ncitron/trade-splitter
ncitron c0788a4
fix tests
ncitron d0962c9
Merge branch 'ncitron/trade-splitter' of github.com:SetProtocol/set-p…
ncitron 3586385
make TradeSplitter adhere to the UniswapV2Router interface
ncitron e31a6a0
use uniswap v2 adapters for trade splitter
ncitron cc92517
cleanup
ncitron 977f3c5
adhere to uniswap interface for getting quotes
ncitron ac29226
change name of contracts
ncitron 6d6220f
improve AMMSplitter tests
ncitron f91dc43
refactoring
ncitron 7a9ce15
fix bug with intermediary tokens with less than 18 decimals
ncitron 2ca3991
refactor
ncitron 3e7f294
add extra tests
ncitron a775af0
update revert messages
ncitron 5293847
improve comments
ncitron edc4d51
add events
ncitron dbeb0e1
use input and output tokens instead of path for events
ncitron File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,14 @@ | ||
| pragma solidity 0.6.10; | ||
|
|
||
| interface IUniswapV2Factory { | ||
| event PairCreated(address indexed token0, address indexed token1, address pair, uint); | ||
|
|
||
| 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 feeTo() external view returns (address); | ||
| function feeToSetter() external view returns (address); | ||
|
|
||
| function createPair(address tokenA, address tokenB) external returns (address pair); | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,272 @@ | ||
| /* | ||
| Copyright 2021 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. | ||
|
|
||
| SPDX-License-Identifier: Apache License, Version 2.0 | ||
| */ | ||
|
|
||
| pragma solidity 0.6.10; | ||
| pragma experimental "ABIEncoderV2"; | ||
|
|
||
| import { ERC20 } from "@openzeppelin/contracts/token/ERC20/ERC20.sol"; | ||
| import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; | ||
|
|
||
| import { IUniswapV2Factory } from "../interfaces/external/IUniswapV2Factory.sol"; | ||
| import { IUniswapV2Router } from "../interfaces/external/IUniswapV2Router.sol"; | ||
| import { PreciseUnitMath } from "../lib/PreciseUnitMath.sol"; | ||
|
|
||
| /** | ||
| * @title TradeSplitter | ||
| * @author Set Protocol | ||
| * | ||
| * Peripheral contract which splits trades efficiently between Uniswap and Sushiswap | ||
ncitron marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| */ | ||
| contract TradeSplitter { | ||
|
|
||
| using SafeMath for uint256; | ||
| using PreciseUnitMath for uint256; | ||
|
|
||
| /* ============ Constants ============ */ | ||
|
|
||
| // address of the Uniswap Router contract | ||
| IUniswapV2Router public immutable uniRouter; | ||
| // address of the Sushiswap Router contract | ||
| IUniswapV2Router public immutable sushiRouter; | ||
| // address of the Uniswap Factory contract | ||
| IUniswapV2Factory public immutable uniFactory; | ||
| // address of the Sushiswap Factory contract | ||
| IUniswapV2Factory public immutable sushiFactory; | ||
|
|
||
| /* =========== Constructor =========== */ | ||
|
|
||
| /** | ||
| * Sets state variables | ||
| * | ||
| * @param _uniRouter the Uniswap router contract | ||
| * @param _sushiRouter the Sushiswap router contract | ||
| */ | ||
| constructor(IUniswapV2Router _uniRouter, IUniswapV2Router _sushiRouter) public { | ||
| uniRouter = _uniRouter; | ||
| sushiRouter = _sushiRouter; | ||
| uniFactory = IUniswapV2Factory(_uniRouter.factory()); | ||
| sushiFactory = IUniswapV2Factory(_sushiRouter.factory()); | ||
| } | ||
|
|
||
| /* ============ External Functions ============= */ | ||
|
|
||
| /** | ||
| * Executes an exact input trade. Splits trade efficiently between Uniswap and Sushiswap | ||
| * | ||
| * @param _amountIn the exact input amount | ||
| * @param _amountOutMin the minimum output amount that must be received | ||
| * @param _path the path to use for the trade (length must be 3 or less) | ||
| * @param _to the address to direct the outputs to | ||
| * @param _deadline the deadline for the trade | ||
| * | ||
| * @return totalOutput the actual output amount | ||
| */ | ||
| function swapExactTokensForTokens( | ||
| uint256 _amountIn, | ||
| uint256 _amountOutMin, | ||
| address[] calldata _path, | ||
| address _to, | ||
| uint256 _deadline | ||
| ) | ||
| external | ||
| returns (uint256 totalOutput) | ||
| { | ||
| require(_path.length <= 3 && _path.length != 0, "TradeSplitter: incorrect path length"); | ||
|
|
||
| ERC20 inputToken = ERC20(_path[0]); | ||
| inputToken.transferFrom(msg.sender, address(this), _amountIn); | ||
|
|
||
| (uint256 uniTradeSize, uint256 sushiTradeSize) = _getTradeSizes(_path, _amountIn); | ||
ncitron marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| _checkApprovals(uniTradeSize, sushiTradeSize, inputToken); | ||
|
|
||
| uint256 uniOutput = _executeTrade(uniRouter, uniTradeSize, _path, _to, _deadline, true); | ||
| uint256 sushiOutput = _executeTrade(sushiRouter, sushiTradeSize, _path, _to, _deadline, true); | ||
|
|
||
| totalOutput = uniOutput.add(sushiOutput); | ||
| require(totalOutput > _amountOutMin, "TradeSplitter: INSUFFICIENT_OUTPUT_AMOUNT"); | ||
ncitron marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| } | ||
|
|
||
| /** | ||
| * Executes an exact output trade. Splits trade efficiently between Uniswap and Sushiswap | ||
| * | ||
| * @param _amountOut the exact output amount | ||
| * @param _amountInMax the maximum input amount that can be spent | ||
| * @param _path the path to use for the trade (length must be 3 or less) | ||
| * @param _to the address to direct the outputs to | ||
| * @param _deadline the deadline for the trade | ||
| * | ||
| * @return totalInput the actual input amount | ||
| */ | ||
| function swapTokensForExactTokens( | ||
| uint256 _amountOut, | ||
| uint256 _amountInMax, | ||
| address[] calldata _path, | ||
| address _to, | ||
| uint256 _deadline | ||
| ) | ||
| external | ||
| returns (uint256 totalInput) | ||
| { | ||
| require(_path.length <= 3 && _path.length != 0, "TradeSplitter: incorrect path length"); | ||
|
|
||
| (uint256 uniTradeSize, uint256 sushiTradeSize) = _getTradeSizes(_path, _amountOut); | ||
|
|
||
| uint256 expectedUniInput = _getTradeInputOrOutput(uniRouter, uniTradeSize, _path, false); | ||
ncitron marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| uint256 expectedSushiInput = _getTradeInputOrOutput(sushiRouter, sushiTradeSize, _path, false); | ||
ncitron marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| ERC20(_path[0]).transferFrom(msg.sender, address(this), expectedUniInput.add(expectedSushiInput)); | ||
ncitron marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| _checkApprovals(expectedUniInput, expectedSushiInput, ERC20(_path[0])); | ||
|
|
||
| uint256 uniInput = _executeTrade(uniRouter, uniTradeSize, _path, _to, _deadline, false); | ||
| uint256 sushiInput = _executeTrade(sushiRouter, sushiTradeSize, _path, _to, _deadline, false); | ||
|
|
||
| totalInput = uniInput.add(sushiInput); | ||
| require(totalInput < _amountInMax, "TradeSplitter: INSUFFICIENT_INPUT_AMOUNT"); | ||
ncitron marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| } | ||
|
|
||
| /* =========== External Getter Functions =========== */ | ||
|
|
||
| /** | ||
| * Returns a quote with an estimated trade output amount | ||
| * | ||
| * @param _amountIn input amount | ||
| * @param _path the trade path to use | ||
| * | ||
| * @return uint256 the expected output amount | ||
| */ | ||
| function getQuoteExactInput(uint256 _amountIn, address[] calldata _path) external view returns (uint256) { | ||
ncitron marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| require(_path.length <= 3 && _path.length != 0, "TradeSplitter: incorrect path length"); | ||
|
|
||
| (uint256 uniTradeSize, uint256 sushiTradeSize) = _getTradeSizes(_path, _amountIn); | ||
|
|
||
| uint256 uniTradeResult = _getTradeInputOrOutput(uniRouter, uniTradeSize, _path, true); | ||
| uint256 sushiTradeResult = _getTradeInputOrOutput(sushiRouter, sushiTradeSize, _path, true); | ||
|
|
||
| return uniTradeResult.add(sushiTradeResult); | ||
| } | ||
|
|
||
| /** | ||
| * Returns a quote with an estimated trade output amount | ||
| * | ||
| * @param _amountOut output amount | ||
| * @param _path the trade path to use | ||
| * | ||
| * @return uint256 the expected input amount | ||
| */ | ||
| function getQuoteExactOutput(uint256 _amountOut, address[] calldata _path) external view returns (uint256) { | ||
ncitron marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| require(_path.length <= 3 && _path.length != 0, "TradeSplitter: incorrect path length"); | ||
|
|
||
| (uint256 uniTradeSize, uint256 sushiTradeSize) = _getTradeSizes(_path, _amountOut); | ||
|
|
||
| uint256 uniTradeResult = _getTradeInputOrOutput(uniRouter, uniTradeSize, _path, false); | ||
| uint256 sushiTradeResult = _getTradeInputOrOutput(sushiRouter, sushiTradeSize, _path, false); | ||
|
|
||
| return uniTradeResult.add(sushiTradeResult); | ||
| } | ||
|
|
||
| /* ============= Internal Functions ============ */ | ||
|
|
||
| function _getTradeSizes(address[] calldata _path, uint256 _size) internal view returns (uint256 uniSize, uint256 sushiSize) { | ||
ncitron marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| if (_path.length == 2) { | ||
| address uniPair = uniFactory.getPair(_path[0], _path[1]); | ||
| uint256 uniValue = ERC20(_path[0]).balanceOf(uniPair); | ||
|
|
||
| address sushiPair = sushiFactory.getPair(_path[0], _path[1]); | ||
| uint256 sushiValue = ERC20(_path[0]).balanceOf(sushiPair); | ||
|
|
||
| uint256 uniPercentage = uniValue.preciseDiv(uniValue.add(sushiValue)); | ||
| uniSize = _size.preciseMul(uniPercentage); | ||
| sushiSize = _size.sub(uniSize); | ||
| } else { | ||
| address uniPairA = uniFactory.getPair(_path[0], _path[1]); | ||
| address uniPairB = uniFactory.getPair(_path[1], _path[2]); | ||
|
|
||
| uint256 uniValueA = ERC20(_path[1]).balanceOf(uniPairA); | ||
| uint256 uniValueB = ERC20(_path[1]).balanceOf(uniPairB); | ||
|
|
||
| if(uniValueA == 0 || uniValueB == 0) return (0, _size); | ||
|
|
||
| address sushiPairA = sushiFactory.getPair(_path[0], _path[1]); | ||
| address sushiPairB = sushiFactory.getPair(_path[1], _path[2]); | ||
|
|
||
| uint256 sushiValueA = ERC20(_path[1]).balanceOf(sushiPairA); | ||
| uint256 sushiValueB = ERC20(_path[1]).balanceOf(sushiPairB); | ||
|
|
||
| if(sushiValueA == 0 || sushiValueB == 0) return (_size, 0); | ||
|
|
||
| uint256 ratio = sushiValueA.add(sushiValueB).preciseMul(uniValueA).preciseMul(uniValueB) | ||
ncitron marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| .preciseDiv(uniValueA.add(uniValueB).preciseMul(sushiValueA).preciseMul(sushiValueB)); | ||
|
|
||
| uint256 uniPercentage = ratio.preciseDiv(ratio.add(PreciseUnitMath.PRECISE_UNIT)); | ||
| uniSize = _size.preciseMul(uniPercentage); | ||
| sushiSize = _size.sub(uniSize); | ||
| } | ||
| } | ||
|
|
||
| function _checkApprovals(uint256 _uniAmount, uint256 _sushiAmount, ERC20 token) internal { | ||
ncitron marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| if (token.allowance(address(this), address(uniRouter)) < _uniAmount) { | ||
| token.approve(address(uniRouter), PreciseUnitMath.MAX_UINT_256); | ||
| } | ||
| if (token.allowance(address(this), address(sushiRouter)) < _sushiAmount) { | ||
| token.approve(address(sushiRouter), PreciseUnitMath.MAX_UINT_256); | ||
| } | ||
| } | ||
|
|
||
| function _executeTrade( | ||
ncitron marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| IUniswapV2Router _router, | ||
| uint256 _size, | ||
| address[] calldata _path, | ||
| address _to, | ||
| uint256 _deadline, | ||
| bool _isExactInput | ||
| ) | ||
| internal | ||
| returns (uint256) | ||
| { | ||
| if (_size == 0) return 0; | ||
|
|
||
| if (_isExactInput) { | ||
| return _router.swapExactTokensForTokens(_size, 0, _path, _to, _deadline)[_path.length.sub(1)]; | ||
| } else { | ||
| _router.swapTokensForExactTokens(_size, uint256(-1), _path, _to, _deadline)[_path.length.sub(1)]; | ||
ncitron marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| } | ||
| } | ||
|
|
||
| function _getTradeInputOrOutput( | ||
ncitron marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| IUniswapV2Router _router, | ||
| uint256 _size, | ||
| address[] calldata _path, | ||
| bool _isExactInput | ||
| ) | ||
| internal | ||
| view | ||
| returns (uint256) | ||
| { | ||
| if (_size == 0) return 0; | ||
|
|
||
| if(_isExactInput) { | ||
| return _router.getAmountsOut(_size, _path)[_path.length.sub(1)]; | ||
| } else { | ||
| return _router.getAmountsIn(_size, _path)[0]; | ||
| } | ||
| } | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.