Skip to content

Uniswap V3 Exchange Adapter #96

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 19 commits into from
Jun 9, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
66 changes: 66 additions & 0 deletions contracts/interfaces/external/ISwapRouter.sol
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity 0.6.10;
pragma experimental ABIEncoderV2;


/// @title Router token swapping functionality
/// @notice Functions for swapping tokens via Uniswap V3
interface ISwapRouter {
struct ExactInputSingleParams {
address tokenIn;
address tokenOut;
uint24 fee;
address recipient;
uint256 deadline;
uint256 amountIn;
uint256 amountOutMinimum;
uint160 sqrtPriceLimitX96;
}

/// @notice Swaps `amountIn` of one token for as much as possible of another token
/// @param params The parameters necessary for the swap, encoded as `ExactInputSingleParams` in calldata
/// @return amountOut The amount of the received token
function exactInputSingle(ExactInputSingleParams calldata params) external payable returns (uint256 amountOut);

struct ExactInputParams {
bytes path;
address recipient;
uint256 deadline;
uint256 amountIn;
uint256 amountOutMinimum;
}

/// @notice Swaps `amountIn` of one token for as much as possible of another along the specified path
/// @param params The parameters necessary for the multi-hop swap, encoded as `ExactInputParams` in calldata
/// @return amountOut The amount of the received token
function exactInput(ExactInputParams calldata params) external payable returns (uint256 amountOut);

struct ExactOutputSingleParams {
address tokenIn;
address tokenOut;
uint24 fee;
address recipient;
uint256 deadline;
uint256 amountOut;
uint256 amountInMaximum;
uint160 sqrtPriceLimitX96;
}

/// @notice Swaps as little as possible of one token for `amountOut` of another token
/// @param params The parameters necessary for the swap, encoded as `ExactOutputSingleParams` in calldata
/// @return amountIn The amount of the input token
function exactOutputSingle(ExactOutputSingleParams calldata params) external payable returns (uint256 amountIn);

struct ExactOutputParams {
bytes path;
address recipient;
uint256 deadline;
uint256 amountOut;
uint256 amountInMaximum;
}

/// @notice Swaps as little as possible of one token for `amountOut` of another along the specified path (reversed)
/// @param params The parameters necessary for the multi-hop swap, encoded as `ExactOutputParams` in calldata
/// @return amountIn The amount of the input token
function exactOutput(ExactOutputParams calldata params) external payable returns (uint256 amountIn);
}
129 changes: 129 additions & 0 deletions contracts/protocol/integration/exchange/UniswapV3ExchangeAdapter.sol
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
/*
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 { BytesLib } from "../../../../external/contracts/uniswap/v3/lib/BytesLib.sol";
import { ISwapRouter } from "../../../interfaces/external/ISwapRouter.sol";


/**
* @title UniswapV3TradeAdapter
* @author Set Protocol
*
* Exchange adapter for Uniswap V3 SwapRouter that encodes trade data
*/
contract UniswapV3ExchangeAdapter {

using BytesLib for bytes;

/* ============= Constants ================= */

// signature of exactInput SwapRouter function
string internal constant EXACT_INPUT = "exactInput((bytes,address,uint256,uint256,uint256))";

/* ============ State Variables ============ */

// Address of Uniswap V3 SwapRouter contract
address public immutable swapRouter;

/* ============ Constructor ============ */

/**
* Set state variables
*
* @param _swapRouter Address of Uniswap V3 SwapRouter
*/
constructor(address _swapRouter) public {
swapRouter = _swapRouter;
}

/* ============ External Getter Functions ============ */

/**
* Return calldata for Uniswap V3 SwapRouter
*
* @param _sourceToken Address of source token to be sold
* @param _destinationToken Address of destination token to buy
* @param _destinationAddress Address that assets should be transferred to
* @param _sourceQuantity Amount of source token to sell
* @param _minDestinationQuantity Min amount of destination token to buy
* @param _data Uniswap V3 path. Equals the output of the generateDataParam function
*
* @return address Target contract address
* @return uint256 Call value
* @return bytes Trade calldata
*/
function getTradeCalldata(
address _sourceToken,
address _destinationToken,
address _destinationAddress,
uint256 _sourceQuantity,
uint256 _minDestinationQuantity,
bytes calldata _data
)
external
view
returns (address, uint256, bytes memory)
{

address sourceFromPath = _data.toAddress(0);
require(_sourceToken == sourceFromPath, "UniswapV3ExchangeAdapter: source token path mismatch");

address destinationFromPath = _data.toAddress(_data.length - 20);
require(_destinationToken == destinationFromPath, "UniswapV3ExchangeAdapter: destination token path mismatch");

ISwapRouter.ExactInputParams memory params = ISwapRouter.ExactInputParams(
_data,
_destinationAddress,
block.timestamp,
_sourceQuantity,
_minDestinationQuantity
);

bytes memory callData = abi.encodeWithSignature(EXACT_INPUT, params);
return (swapRouter, 0, callData);
}

/**
* Returns the address to approve source tokens to for trading. This is the Uniswap SwapRouter address
*
* @return address Address of the contract to approve tokens to
*/
function getSpender() external view returns (address) {
return swapRouter;
}

/**
* Returns the appropriate _data argument for getTradeCalldata. Equal to the encodePacked path with the
* fee of each hop between it, e.g [token1, fee1, token2, fee2, token3]. Note: _fees.length == _path.length - 1
*
* @param _path array of addresses to use as the path for the trade
* @param _fees array of uint24 representing the pool fee to use for each hop
*/
function generateDataParam(address[] calldata _path, uint24[] calldata _fees) external pure returns (bytes memory) {
bytes memory data = "";
for (uint256 i = 0; i < _path.length - 1; i++) {
data = abi.encodePacked(data, _path[i], _fees[i]);
}

// last encode has no fee associated with it since _fees.length == _path.length - 1
return abi.encodePacked(data, _path[_path.length - 1]);
}
}
2 changes: 1 addition & 1 deletion test/fixtures/uniswapV3.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ describe("UniswapV3Fixture", () => {

const slot0 = await pool.slot0();

const expectedSqrtPrice = uniswapV3Fixture._getSqrtPriceX96(1e-12);
const expectedSqrtPrice = uniswapV3Fixture._getSqrtPriceX96(1e12);

expect(slot0.sqrtPriceX96).to.eq(expectedSqrtPrice);
});
Expand Down
189 changes: 189 additions & 0 deletions test/protocol/integration/exchange/uniswapV3ExchangeAdapter.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,189 @@
import "module-alias/register";

import { BigNumber, BigNumberish } from "@ethersproject/bignumber";
import { solidityPack } from "ethers/lib/utils";

import { Address, Bytes } from "@utils/types";
import { Account } from "@utils/test/types";
import { ZERO } from "@utils/constants";
import { UniswapV3ExchangeAdapter } from "@utils/contracts";
import DeployHelper from "@utils/deploys";
import { ether } from "@utils/index";
import {
addSnapshotBeforeRestoreAfterEach,
getAccounts,
getSystemFixture,
getWaffleExpect,
getLastBlockTimestamp,
getUniswapV3Fixture,
getRandomAddress
} from "@utils/test/index";

import { SystemFixture, UniswapV3Fixture } from "@utils/fixtures";

const expect = getWaffleExpect();

describe("UniswapV3ExchangeAdapter", () => {
let owner: Account;
let mockSetToken: Account;
let deployer: DeployHelper;
let setup: SystemFixture;
let uniswapV3Fixture: UniswapV3Fixture;

let uniswapV3ExchangeAdapter: UniswapV3ExchangeAdapter;

before(async () => {
[
owner,
mockSetToken,
] = await getAccounts();

deployer = new DeployHelper(owner.wallet);
setup = getSystemFixture(owner.address);
await setup.initialize();

uniswapV3Fixture = getUniswapV3Fixture(owner.address);
await uniswapV3Fixture.initialize(
owner,
setup.weth,
2500,
setup.wbtc,
35000,
setup.dai
);

uniswapV3ExchangeAdapter = await deployer.adapters.deployUniswapV3ExchangeAdapter(uniswapV3Fixture.swapRouter.address);
});

addSnapshotBeforeRestoreAfterEach();

describe("#constructor", async () => {
let subjectSwapRouter: Address;

beforeEach(async () => {
subjectSwapRouter = uniswapV3Fixture.swapRouter.address;
});

async function subject(): Promise<any> {
return await deployer.adapters.deployUniswapV3ExchangeAdapter(subjectSwapRouter);
}

it("should have the correct SwapRouter address", async () => {
const deployedUniswapV3ExchangeAdapter = await subject();

const actualRouterAddress = await deployedUniswapV3ExchangeAdapter.swapRouter();
expect(actualRouterAddress).to.eq(uniswapV3Fixture.swapRouter.address);
});
});

describe("#getSpender", async () => {
async function subject(): Promise<any> {
return await uniswapV3ExchangeAdapter.getSpender();
}

it("should return the correct spender address", async () => {
const spender = await subject();

expect(spender).to.eq(uniswapV3Fixture.swapRouter.address);
});
});

describe("#getTradeCalldata", async () => {

let subjectMockSetToken: Address;
let subjectSourceToken: Address;
let subjectDestinationToken: Address;
let subjectSourceQuantity: BigNumber;
let subjectMinDestinationQuantity: BigNumber;
let subjectPath: Bytes;

beforeEach(async () => {
subjectSourceToken = setup.wbtc.address;
subjectSourceQuantity = BigNumber.from(100000000);
subjectDestinationToken = setup.weth.address;
subjectMinDestinationQuantity = ether(25);

subjectMockSetToken = mockSetToken.address;

subjectPath = solidityPack(["address", "uint24", "address"], [subjectSourceToken, BigNumber.from(3000), subjectDestinationToken]);
});

async function subject(): Promise<any> {
return await uniswapV3ExchangeAdapter.getTradeCalldata(
subjectSourceToken,
subjectDestinationToken,
subjectMockSetToken,
subjectSourceQuantity,
subjectMinDestinationQuantity,
subjectPath,
);
}

it("should return the correct trade calldata", async () => {
const calldata = await subject();
const callTimestamp = await getLastBlockTimestamp();

const expectedCallData = uniswapV3Fixture.swapRouter.interface.encodeFunctionData("exactInput", [{
path: subjectPath,
recipient: mockSetToken.address,
deadline: callTimestamp,
amountIn: subjectSourceQuantity,
amountOutMinimum: subjectMinDestinationQuantity,
}]);

expect(JSON.stringify(calldata)).to.eq(JSON.stringify([uniswapV3Fixture.swapRouter.address, ZERO, expectedCallData]));
});

context("when source token does not match path", async () => {
beforeEach(async () => {
subjectSourceToken = await getRandomAddress();
});

it("should revert", async () => {
await expect(subject()).to.be.revertedWith("UniswapV3ExchangeAdapter: source token path mismatch");
});
});

context("when destination token does not match path", async () => {
beforeEach(async () => {
subjectDestinationToken = await getRandomAddress();
});

it("should revert", async () => {
await expect(subject()).to.be.revertedWith("UniswapV3ExchangeAdapter: destination token path mismatch");
});
});
});

describe("#generateDataParam", async () => {

let subjectToken1: Address;
let subjectFee1: BigNumberish;
let subjectToken2: Address;
let subjectFee2: BigNumberish;
let subjectToken3: Address;

beforeEach(async () => {
subjectToken1 = setup.wbtc.address;
subjectFee1 = 3000;
subjectToken2 = setup.weth.address;
subjectFee2 = 500;
subjectToken3 = setup.weth.address;
});

async function subject(): Promise<string> {
return await uniswapV3ExchangeAdapter.generateDataParam([subjectToken1, subjectToken2, subjectToken3], [subjectFee1, subjectFee2]);
}

it("should create the correct path data", async () => {
const data = await subject();

const expectedData = solidityPack(
["address", "uint24", "address", "uint24", "address"],
[subjectToken1, subjectFee1, subjectToken2, subjectFee2, subjectToken3]
);

expect(data).to.eq(expectedData);
});
});
});
Loading