Skip to content
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

feat/Interact directly with the pool in Uniswap connector #136

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
5 changes: 5 additions & 0 deletions src/chains/ethereum/ethereum.ts
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,11 @@ export class Ethereum extends EthereumBase implements Ethereumish {
return this._metricsLogInterval;
}

// in place for mocking
public get provider() {
return super.provider;
}

/**
* Automatically update the prevailing gas price on the network.
*
Expand Down
9 changes: 9 additions & 0 deletions src/connectors/uniswap/uniswap.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,9 @@ export namespace UniswapConfig {
tradingTypes: (type: string) => Array<string>;
chainType: string;
availableNetworks: Array<AvailableNetworks>;
useRouter?: boolean;
feeTier?: string;
quoterContractAddress: (network: string) => string;
}

export const config: NetworkConfig = {
Expand Down Expand Up @@ -56,5 +59,11 @@ export namespace UniswapConfig {
),
},
],
useRouter: ConfigManagerV2.getInstance().get(`uniswap.useRouter`),
feeTier: ConfigManagerV2.getInstance().get(`uniswap.feeTier`),
quoterContractAddress: (network: string) =>
ConfigManagerV2.getInstance().get(
`uniswap.contractAddresses.${network}.uniswapV3QuoterV2ContractAddress`
),
};
}
257 changes: 212 additions & 45 deletions src/connectors/uniswap/uniswap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,32 @@ import {
} from '@ethersproject/contracts';
import { AlphaRouter } from '@uniswap/smart-order-router';
import { Trade, SwapRouter } from '@uniswap/router-sdk';
import { MethodParameters } from '@uniswap/v3-sdk';
import {
FeeAmount,
MethodParameters,
Pool,
SwapQuoter,
Trade as UniswapV3Trade,
Route,
FACTORY_ADDRESS,
} from '@uniswap/v3-sdk';
import { abi as IUniswapV3PoolABI } from '@uniswap/v3-core/artifacts/contracts/interfaces/IUniswapV3Pool.sol/IUniswapV3Pool.json';
import { abi as IUniswapV3FactoryABI } from '@uniswap/v3-core/artifacts/contracts/interfaces/IUniswapV3Factory.sol/IUniswapV3Factory.json';
import {
Token,
CurrencyAmount,
Percent,
TradeType,
Currency,
} from '@uniswap/sdk-core';
import { BigNumber, Transaction, Wallet } from 'ethers';
import {
BigNumber,
Transaction,
Wallet,
Contract,
utils,
constants,
} from 'ethers';
import { logger } from '../../services/logger';
import { percentRegexp } from '../../services/config-manager-v2';
import { Ethereum } from '../../chains/ethereum/ethereum';
Expand All @@ -35,6 +52,9 @@ export class Uniswap implements Uniswapish {
private chainId;
private tokenList: Record<string, Token> = {};
private _ready: boolean = false;
private readonly _useRouter: boolean;
private readonly _feeTier: FeeAmount;
private readonly _quoterContractAddress: string;

private constructor(chain: string, network: string) {
const config = UniswapConfig.config;
Expand All @@ -53,6 +73,20 @@ export class Uniswap implements Uniswapish {
this._routerAbi = routerAbi.abi;
this._gasLimitEstimate = UniswapConfig.config.gasLimitEstimate;
this._router = config.uniswapV3SmartOrderRouterAddress(network);

if (config.useRouter === false && config.feeTier == null) {
throw new Error('Must specify fee tier if not using router');
}
if (config.useRouter === false && config.quoterContractAddress == null) {
throw new Error(
'Must specify quoter contract address if not using router'
);
}
this._useRouter = config.useRouter ?? true;
this._feeTier = config.feeTier
? FeeAmount[config.feeTier as keyof typeof FeeAmount]
: FeeAmount.MEDIUM;
this._quoterContractAddress = config.quoterContractAddress(network);
}

public static getInstance(chain: string, network: string): Uniswap {
Expand Down Expand Up @@ -181,30 +215,61 @@ export class Uniswap implements Uniswapish {
`Fetching trade data for ${baseToken.address}-${quoteToken.address}.`
);

const route = await this._alphaRouter.route(
nativeTokenAmount,
quoteToken,
TradeType.EXACT_INPUT,
undefined,
{
maxSwapsPerPath: this.maximumHops,
}
);
if (this._useRouter) {
const route = await this._alphaRouter.route(
nativeTokenAmount,
quoteToken,
TradeType.EXACT_INPUT,
undefined,
{
maxSwapsPerPath: this.maximumHops,
}
);

if (!route) {
throw new UniswapishPriceError(
`priceSwapIn: no trade pair found for ${baseToken} to ${quoteToken}.`
if (!route) {
throw new UniswapishPriceError(
`priceSwapIn: no trade pair found for ${baseToken.address} to ${quoteToken.address}.`
);
}
logger.info(
`Best trade for ${baseToken.address}-${quoteToken.address}: ` +
`${route.trade.executionPrice.toFixed(6)}` +
`${baseToken.symbol}.`
);
const expectedAmount = route.trade.minimumAmountOut(
this.getAllowedSlippage(allowedSlippage)
);
return { trade: route.trade, expectedAmount };
} else {
const pool = await this.getPool(baseToken, quoteToken, this._feeTier);
if (!pool) {
throw new UniswapishPriceError(
`priceSwapIn: no trade pair found for ${baseToken.address} to ${quoteToken.address}.`
);
}
const swapRoute = new Route([pool], baseToken, quoteToken);
const quotedAmount = await this.getQuote(
swapRoute,
quoteToken,
nativeTokenAmount,
TradeType.EXACT_INPUT
);
const trade = UniswapV3Trade.createUncheckedTrade({
route: swapRoute,
inputAmount: nativeTokenAmount,
outputAmount: quotedAmount,
tradeType: TradeType.EXACT_INPUT,
});
logger.info(
`Best trade for ${baseToken.address}-${quoteToken.address}: ` +
`${trade.executionPrice.toFixed(6)}` +
`${baseToken.symbol}.`
);
const expectedAmount = trade.minimumAmountOut(
this.getAllowedSlippage(allowedSlippage)
);
return { trade, expectedAmount };
}
logger.info(
`Best trade for ${baseToken.address}-${quoteToken.address}: ` +
`${route.trade.executionPrice.toFixed(6)}` +
`${baseToken.symbol}.`
);
const expectedAmount = route.trade.minimumAmountOut(
this.getAllowedSlippage(allowedSlippage)
);
return { trade: route.trade, expectedAmount };
}

/**
Expand All @@ -228,30 +293,62 @@ export class Uniswap implements Uniswapish {
logger.info(
`Fetching pair data for ${quoteToken.address}-${baseToken.address}.`
);
const route = await this._alphaRouter.route(
nativeTokenAmount,
quoteToken,
TradeType.EXACT_OUTPUT,
undefined,
{
maxSwapsPerPath: this.maximumHops,

if (this._useRouter) {
const route = await this._alphaRouter.route(
nativeTokenAmount,
quoteToken,
TradeType.EXACT_OUTPUT,
undefined,
{
maxSwapsPerPath: this.maximumHops,
}
);
if (!route) {
throw new UniswapishPriceError(
`priceSwapOut: no trade pair found for ${quoteToken.address} to ${baseToken.address}.`
);
}
);
if (!route) {
throw new UniswapishPriceError(
`priceSwapOut: no trade pair found for ${quoteToken.address} to ${baseToken.address}.`
logger.info(
`Best trade for ${quoteToken.address}-${baseToken.address}: ` +
`${route.trade.executionPrice.invert().toFixed(6)} ` +
`${baseToken.symbol}.`
);
}
logger.info(
`Best trade for ${quoteToken.address}-${baseToken.address}: ` +
`${route.trade.executionPrice.invert().toFixed(6)} ` +
`${baseToken.symbol}.`
);

const expectedAmount = route.trade.maximumAmountIn(
this.getAllowedSlippage(allowedSlippage)
);
return { trade: route.trade, expectedAmount };
const expectedAmount = route.trade.maximumAmountIn(
this.getAllowedSlippage(allowedSlippage)
);
return { trade: route.trade, expectedAmount };
} else {
const pool = await this.getPool(quoteToken, baseToken, this._feeTier);
if (!pool) {
throw new UniswapishPriceError(
`priceSwapOut: no trade pair found for ${quoteToken.address} to ${baseToken.address}.`
);
}
const swapRoute = new Route([pool], quoteToken, baseToken);
const quotedAmount = await this.getQuote(
swapRoute,
quoteToken,
nativeTokenAmount,
TradeType.EXACT_OUTPUT
);
const trade = UniswapV3Trade.createUncheckedTrade({
route: swapRoute,
inputAmount: quotedAmount,
outputAmount: nativeTokenAmount,
tradeType: TradeType.EXACT_OUTPUT,
});
logger.info(
`Best trade for ${baseToken.address}-${quoteToken.address}: ` +
`${trade.executionPrice.invert().toFixed(6)}` +
`${baseToken.symbol}.`
);
const expectedAmount = trade.maximumAmountIn(
this.getAllowedSlippage(allowedSlippage)
);
return { trade, expectedAmount };
}
}

/**
Expand Down Expand Up @@ -308,7 +405,7 @@ export class Uniswap implements Uniswapish {
} else {
tx = await wallet.sendTransaction({
data: methodParameters.calldata,
to: this.router,
to: uniswapRouter,
gasPrice: (gasPrice * 1e9).toFixed(0),
gasLimit: gasLimit.toFixed(0),
value: methodParameters.value,
Expand All @@ -320,4 +417,74 @@ export class Uniswap implements Uniswapish {
}
);
}

private async getPool(
tokenA: Token,
tokenB: Token,
feeTier: FeeAmount
): Promise<Pool | null> {
const uniswapFactory = new Contract(
FACTORY_ADDRESS,
IUniswapV3FactoryABI,
this.chain.provider
);
// Use Uniswap V3 factory to get pool address instead of `Pool.getAddress` to check if pool exists.
const poolAddress = await uniswapFactory.getPool(
tokenA.address,
tokenB.address,
feeTier
);
if (poolAddress === constants.AddressZero) {
return null;
}
const poolContract = new Contract(
poolAddress,
IUniswapV3PoolABI,
this.chain.provider
);

const [liquidity, slot0] = await Promise.all([
poolContract.liquidity(),
poolContract.slot0(),
]);
const [sqrtPriceX96, tick] = slot0;

const pool = new Pool(
tokenA,
tokenB,
this._feeTier,
sqrtPriceX96,
liquidity,
tick
);

return pool;
}

private async getQuote(
swapRoute: Route<Token, Token>,
quoteToken: Token,
amount: CurrencyAmount<Token>,
tradeType: TradeType
) {
const { calldata } = await SwapQuoter.quoteCallParameters(
swapRoute,
amount,
tradeType,
{ useQuoterV2: true }
);
const quoteCallReturnData = await this.chain.provider.call({
to: this._quoterContractAddress,
data: calldata,
});
const quoteTokenRawAmount = utils.defaultAbiCoder.decode(
['uint256'],
quoteCallReturnData
);
const qouteTokenAmount = CurrencyAmount.fromRawAmount(
quoteToken,
quoteTokenRawAmount.toString()
);
return qouteTokenAmount;
}
}
1 change: 0 additions & 1 deletion src/services/common-interfaces.ts
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,6 @@ export type UniswapishTrade =
| TradeQuickswap
| TradeTraderjoe
| SushiswapTrade<SushiToken, SushiToken, SushiTradeType>
| UniswapV3Trade<Currency, UniswapCoreToken, TradeType>
| TradeUniswap
| TradeDefikingdoms
| DefiraTrade<UniswapCoreToken, UniswapCoreToken, TradeType>
Expand Down
7 changes: 6 additions & 1 deletion src/services/schema/uniswap-schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,19 @@
"gasLimitEstimate": { "type": "integer" },
"ttl": { "type": "integer" },
"maximumHops": { "type": "integer" },
"useRouter": { "type": "boolean" },
"feeTier": {
"enum": ["LOWEST", "LOW", "MEDIUM", "HIGH"]
},
"contractAddresses": {
"type": "object",
"patternProperties": {
"^\\w+$": {
"type": "object",
"properties": {
"uniswapV3SmartOrderRouterAddress": { "type": "string" },
"uniswapV3NftManagerAddress": { "type": "string" }
"uniswapV3NftManagerAddress": { "type": "string" },
"uniswapV3QuoterV2ContractAddress": { "type": "string" }
},
"required": [
"uniswapV3SmartOrderRouterAddress",
Expand Down
Loading
Loading