mirror of
https://github.com/orionprotocol/sdk.git
synced 2026-03-17 08:41:38 +03:00
Merge pull request #186 from orionprotocol/feature/cross-dex-support
Added cross dex swap support
This commit is contained in:
9144
package-lock.json
generated
9144
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@orionprotocol/sdk",
|
||||
"version": "0.20.6",
|
||||
"version": "0.20.7-rc1",
|
||||
"description": "Orion Protocol SDK",
|
||||
"main": "./lib/index.cjs",
|
||||
"module": "./lib/index.js",
|
||||
@@ -66,6 +66,7 @@
|
||||
"@typescript-eslint/parser": "^6.4.0",
|
||||
"babel-loader": "^9.1.2",
|
||||
"concurrently": "^8.1.0",
|
||||
"esbuild": "^0.13.4",
|
||||
"eslint": "^8.47.0",
|
||||
"eslint-config-airbnb-base": "^15.0.0",
|
||||
"eslint-config-standard": "^17.1.0",
|
||||
@@ -87,7 +88,7 @@
|
||||
"@babel/runtime": "^7.21.0",
|
||||
"@ethersproject/abstract-signer": "^5.7.0",
|
||||
"@ethersproject/providers": "^5.7.2",
|
||||
"@orionprotocol/contracts": "1.17.0",
|
||||
"@orionprotocol/contracts": "1.19.5",
|
||||
"bignumber.js": "^9.1.1",
|
||||
"bson-objectid": "^2.0.4",
|
||||
"buffer": "^6.0.3",
|
||||
|
||||
28
src/Unit/Exchange/callGenerators/curve.ts
Normal file
28
src/Unit/Exchange/callGenerators/curve.ts
Normal file
@@ -0,0 +1,28 @@
|
||||
import { SwapExecutor__factory, CurveRegistry__factory } from "@orionprotocol/contracts/lib/ethers-v6/index.js"
|
||||
import type { BigNumberish, JsonRpcProvider } from "ethers"
|
||||
import { addCallParams } from "./utils.js"
|
||||
import type { SingleSwap } from "../../../types.js"
|
||||
|
||||
export async function generateCurveStableSwapCall(
|
||||
amount: BigNumberish,
|
||||
to: string,
|
||||
swap: SingleSwap,
|
||||
provider: JsonRpcProvider,
|
||||
curveRegistry: string
|
||||
) {
|
||||
const executorInterface = SwapExecutor__factory.createInterface()
|
||||
const registry = CurveRegistry__factory.connect(curveRegistry, provider)
|
||||
const { pool, assetIn, assetOut } = swap
|
||||
const [i, j,] = await registry.get_coin_indices(pool, assetIn, assetOut)
|
||||
|
||||
let calldata = executorInterface.encodeFunctionData('curveSwapStableAmountIn', [
|
||||
pool,
|
||||
assetOut,
|
||||
i,
|
||||
j,
|
||||
to,
|
||||
amount,
|
||||
])
|
||||
|
||||
return addCallParams(calldata)
|
||||
}
|
||||
37
src/Unit/Exchange/callGenerators/erc20.ts
Normal file
37
src/Unit/Exchange/callGenerators/erc20.ts
Normal file
@@ -0,0 +1,37 @@
|
||||
import { SwapExecutor__factory } from "@orionprotocol/contracts/lib/ethers-v6/index.js"
|
||||
import type { BigNumberish } from "ethers"
|
||||
import { type CallParams, addCallParams } from "./utils.js"
|
||||
import type { AddressLike } from "ethers"
|
||||
|
||||
export async function generateTransferCall(
|
||||
token: AddressLike,
|
||||
target: AddressLike,
|
||||
amount: BigNumberish,
|
||||
callParams?: CallParams
|
||||
) {
|
||||
|
||||
const executorInterface = SwapExecutor__factory.createInterface()
|
||||
const calldata = executorInterface.encodeFunctionData('safeTransfer', [
|
||||
token,
|
||||
target,
|
||||
amount
|
||||
])
|
||||
|
||||
return addCallParams(calldata, callParams)
|
||||
}
|
||||
|
||||
export async function generateApproveCall(
|
||||
token: AddressLike,
|
||||
target: AddressLike,
|
||||
amount: BigNumberish,
|
||||
callParams?: CallParams
|
||||
) {
|
||||
const executorInterface = SwapExecutor__factory.createInterface()
|
||||
const calldata = executorInterface.encodeFunctionData('safeApprove', [
|
||||
token,
|
||||
target,
|
||||
amount
|
||||
])
|
||||
|
||||
return addCallParams(calldata, callParams)
|
||||
}
|
||||
54
src/Unit/Exchange/callGenerators/uniswapV2.ts
Normal file
54
src/Unit/Exchange/callGenerators/uniswapV2.ts
Normal file
@@ -0,0 +1,54 @@
|
||||
import { SwapExecutor__factory } from "@orionprotocol/contracts/lib/ethers-v5/index.js"
|
||||
import { SafeArray } from "../../../utils/safeGetters.js"
|
||||
import { type BytesLike, type BigNumberish, concat, ethers, toBeHex } from "ethers"
|
||||
import { addCallParams, generateCalls } from "./utils.js"
|
||||
import type { SingleSwap } from "../../../types.js"
|
||||
|
||||
export async function generateUni2Calls(
|
||||
path: SafeArray<SingleSwap>,
|
||||
recipient: string
|
||||
) {
|
||||
const executorInterface = SwapExecutor__factory.createInterface()
|
||||
const calls: BytesLike[] = []
|
||||
if (path.length > 1) {
|
||||
for (let i = 0; i < path.length - 1; ++i) {
|
||||
const currentSwap = path.get(i)
|
||||
const nextSwap = path.get(i + 1)
|
||||
|
||||
const call = await generateUni2Call(
|
||||
currentSwap.pool,
|
||||
currentSwap.assetIn,
|
||||
currentSwap.assetOut,
|
||||
nextSwap.pool
|
||||
)
|
||||
calls.push(call)
|
||||
}
|
||||
}
|
||||
const lastSwap = path.last();
|
||||
const calldata = executorInterface.encodeFunctionData('swapUniV2', [
|
||||
lastSwap.pool,
|
||||
lastSwap.assetIn,
|
||||
lastSwap.assetOut,
|
||||
ethers.AbiCoder.defaultAbiCoder().encode(['uint256'], [concat(['0x03', recipient])]),
|
||||
])
|
||||
calls.push(addCallParams(calldata))
|
||||
|
||||
return generateCalls(calls)
|
||||
}
|
||||
|
||||
export async function generateUni2Call(
|
||||
pool: string,
|
||||
assetIn: string,
|
||||
assetOut: string,
|
||||
recipient: string,
|
||||
fee: BigNumberish = 3,
|
||||
) {
|
||||
const executorInterface = SwapExecutor__factory.createInterface()
|
||||
const calldata = executorInterface.encodeFunctionData('swapUniV2', [
|
||||
pool,
|
||||
assetIn,
|
||||
assetOut,
|
||||
ethers.AbiCoder.defaultAbiCoder().encode(['uint256'], [concat([toBeHex(fee), recipient])]),
|
||||
])
|
||||
return addCallParams(calldata)
|
||||
}
|
||||
92
src/Unit/Exchange/callGenerators/uniswapV3.ts
Normal file
92
src/Unit/Exchange/callGenerators/uniswapV3.ts
Normal file
@@ -0,0 +1,92 @@
|
||||
import { SwapExecutor__factory, UniswapV3Pool__factory } from "@orionprotocol/contracts/lib/ethers-v6/index.js"
|
||||
import { type BigNumberish , type BytesLike, ethers, JsonRpcProvider } from "ethers"
|
||||
import { SafeArray } from "../../../utils/safeGetters.js"
|
||||
import { addCallParams, generateCalls } from "./utils.js"
|
||||
import type { SingleSwap } from "../../../types.js"
|
||||
|
||||
export async function generateUni3Call(
|
||||
swap: SingleSwap,
|
||||
amount: BigNumberish | undefined,
|
||||
recipient: string,
|
||||
provider: JsonRpcProvider
|
||||
) {
|
||||
if (typeof amount === 'undefined') amount = 0
|
||||
|
||||
const encodedPool = await encodePoolV3(swap.pool, swap.assetIn, swap.assetOut, provider)
|
||||
const executorInterface = SwapExecutor__factory.createInterface()
|
||||
let calldata = executorInterface.encodeFunctionData('uniswapV3SingleSwapTo', [encodedPool, recipient, amount])
|
||||
|
||||
return addCallParams(calldata)
|
||||
}
|
||||
|
||||
export async function generateOrion3Call(
|
||||
swap: SingleSwap,
|
||||
amount: BigNumberish | undefined,
|
||||
recipient: string,
|
||||
provider: JsonRpcProvider
|
||||
) {
|
||||
if (amount === undefined) amount = 0
|
||||
|
||||
const encodedPool = await encodePoolV3(swap.pool, swap.assetIn, swap.assetOut, provider)
|
||||
const executorInterface = SwapExecutor__factory.createInterface()
|
||||
const calldata = executorInterface.encodeFunctionData('orionV3SingleSwapTo', [encodedPool, recipient, amount])
|
||||
|
||||
return addCallParams(calldata)
|
||||
}
|
||||
|
||||
export async function generateUni3Calls(
|
||||
path: SafeArray<SingleSwap>,
|
||||
amount: BigNumberish,
|
||||
recipient: string,
|
||||
provider: JsonRpcProvider
|
||||
) {
|
||||
const encodedPools: BigNumberish[] = []
|
||||
for (const swap of path) {
|
||||
const encodedPool = await encodePoolV3(swap.pool, swap.assetIn, swap.assetOut, provider)
|
||||
encodedPools.push(encodedPool)
|
||||
}
|
||||
const executorInterface = SwapExecutor__factory.createInterface()
|
||||
let calldata = executorInterface.encodeFunctionData('uniswapV3SwapTo', [encodedPools, recipient, amount])
|
||||
calldata = addCallParams(calldata)
|
||||
|
||||
return generateCalls([calldata])
|
||||
}
|
||||
|
||||
export async function generateOrion3Calls(
|
||||
path: SafeArray<SingleSwap>,
|
||||
amount: BigNumberish,
|
||||
recipient: string,
|
||||
provider: JsonRpcProvider
|
||||
) {
|
||||
const encodedPools: BigNumberish[] = []
|
||||
for (const swap of path) {
|
||||
const encodedPool = await encodePoolV3(swap.pool, swap.assetIn, swap.assetOut, provider)
|
||||
encodedPools.push(encodedPool)
|
||||
}
|
||||
const executorInterface = SwapExecutor__factory.createInterface()
|
||||
let calldata = executorInterface.encodeFunctionData('orionV3SwapTo', [encodedPools, recipient, amount])
|
||||
calldata = addCallParams(calldata)
|
||||
|
||||
return generateCalls([calldata])
|
||||
}
|
||||
|
||||
export async function encodePoolV3(
|
||||
poolAddress: string,
|
||||
assetInAddress: string,
|
||||
assetOutAddress: string,
|
||||
provider: JsonRpcProvider
|
||||
) {
|
||||
const pool = UniswapV3Pool__factory.connect(poolAddress, provider)
|
||||
const token0 = await pool.token0()
|
||||
const zeroForOne = token0.toLowerCase() === assetInAddress.toLowerCase()
|
||||
const unwrapWETH = assetOutAddress === ethers.ZeroAddress
|
||||
|
||||
let encodedPool = ethers.solidityPacked(['uint256'], [await pool.getAddress()])
|
||||
encodedPool = ethers.dataSlice(encodedPool, 1)
|
||||
let firstByte = 0
|
||||
if (unwrapWETH) firstByte += 32
|
||||
if (!zeroForOne) firstByte += 128
|
||||
const encodedFirstByte = ethers.solidityPacked(['uint8'], [firstByte])
|
||||
encodedPool = ethers.hexlify(ethers.concat([encodedFirstByte, encodedPool]))
|
||||
return encodedPool
|
||||
}
|
||||
99
src/Unit/Exchange/callGenerators/utils.ts
Normal file
99
src/Unit/Exchange/callGenerators/utils.ts
Normal file
@@ -0,0 +1,99 @@
|
||||
import { ERC20__factory, SwapExecutor__factory } from "@orionprotocol/contracts/lib/ethers-v6/index.js"
|
||||
import type { AddressLike } from "ethers"
|
||||
import { type BytesLike, ethers, type BigNumberish } from "ethers"
|
||||
|
||||
const EXECUTOR_SWAP_FUNCTION = 'func_70LYiww'
|
||||
|
||||
export type CallParams = {
|
||||
isMandatory?: boolean,
|
||||
target?: string,
|
||||
gaslimit?: BigNumberish,
|
||||
value?: BigNumberish
|
||||
}
|
||||
|
||||
export type PatchParams = {
|
||||
skipOnZeroAmount?: boolean,
|
||||
skipCallDataPatching?: boolean,
|
||||
skipValuePatching?: boolean
|
||||
}
|
||||
|
||||
export function pathCallWithBalance(
|
||||
calldata: BytesLike,
|
||||
tokenAddress: AddressLike,
|
||||
patchParams: PatchParams = { skipCallDataPatching: false, skipValuePatching: true }
|
||||
) {
|
||||
const executorInterface = SwapExecutor__factory.createInterface()
|
||||
const skipMaskAndOffset = createPatchMask(calldata, patchParams)
|
||||
calldata = executorInterface.encodeFunctionData("patchCallWithTokenBalance", [
|
||||
calldata,
|
||||
skipMaskAndOffset,
|
||||
tokenAddress,
|
||||
ethers.MaxUint256])
|
||||
return addCallParams(calldata)
|
||||
}
|
||||
|
||||
export function addCallParams(
|
||||
calldata: BytesLike,
|
||||
callParams?: CallParams
|
||||
) {
|
||||
let firstByte = 0
|
||||
if (callParams) {
|
||||
if (callParams.value !== undefined) {
|
||||
firstByte += 16 // 00010000
|
||||
const encodedValue = ethers.solidityPacked(['uint128'], [callParams.value])
|
||||
calldata = ethers.hexlify(ethers.concat([encodedValue, calldata]))
|
||||
}
|
||||
if (callParams.target !== undefined) {
|
||||
firstByte += 32 // 00100000
|
||||
const encodedAddress = ethers.solidityPacked(['address'], [callParams.target])
|
||||
calldata = ethers.hexlify(ethers.concat([encodedAddress, calldata]))
|
||||
}
|
||||
if (callParams.gaslimit !== undefined) {
|
||||
firstByte += 64 // 01000000
|
||||
const encodedGaslimit = ethers.solidityPacked(['uint32'], [callParams.gaslimit])
|
||||
calldata = ethers.hexlify(ethers.concat([encodedGaslimit, calldata]))
|
||||
}
|
||||
if (callParams.isMandatory !== undefined) firstByte += 128 // 10000000
|
||||
}
|
||||
|
||||
const encodedFirstByte = ethers.solidityPacked(['uint8'], [firstByte])
|
||||
calldata = ethers.hexlify(ethers.concat([encodedFirstByte, calldata]))
|
||||
return calldata
|
||||
}
|
||||
|
||||
export function createPatchMask(calldata: BytesLike, patchParams?: PatchParams) {
|
||||
let firstByte = 0
|
||||
let mask = ethers.solidityPacked(["uint256"], [(calldata.length - 4) / 2 - 32]) //finding offset of last 32 bytes slot in calldata
|
||||
mask = ethers.dataSlice(mask, 1)
|
||||
if (patchParams) {
|
||||
if (patchParams.skipOnZeroAmount !== undefined && patchParams.skipOnZeroAmount === false) {
|
||||
firstByte += 32
|
||||
}
|
||||
if (patchParams.skipCallDataPatching !== undefined && patchParams.skipCallDataPatching) {
|
||||
firstByte += 64
|
||||
}
|
||||
if (patchParams.skipValuePatching !== undefined && patchParams.skipValuePatching) {
|
||||
firstByte += 128
|
||||
}
|
||||
}
|
||||
const encodedFirstByte = ethers.solidityPacked(["uint8"], [firstByte])
|
||||
mask = ethers.hexlify(ethers.concat([encodedFirstByte, mask]))
|
||||
return mask
|
||||
}
|
||||
|
||||
export function generateCalls(calls: BytesLike[]) {
|
||||
const executorInterface = SwapExecutor__factory.createInterface()
|
||||
return '0x' + executorInterface.encodeFunctionData(EXECUTOR_SWAP_FUNCTION, [ethers.ZeroAddress, calls]).slice(74)
|
||||
}
|
||||
|
||||
export async function exchangeToNativeDecimals(token: AddressLike, amount: BigNumberish, provider: ethers.JsonRpcProvider) {
|
||||
token = await token
|
||||
if (typeof token !== "string") token = await token.getAddress()
|
||||
|
||||
let decimals = 18n
|
||||
if (token !== ethers.ZeroAddress) {
|
||||
const contract = ERC20__factory.connect(token, provider)
|
||||
decimals = BigInt(await contract.decimals())
|
||||
}
|
||||
return BigInt(amount) * (BigInt(10) ** decimals) / (BigInt(10) ** 8n)
|
||||
}
|
||||
@@ -1,35 +1,25 @@
|
||||
import type { ExchangeWithGenericSwap } from '@orionprotocol/contracts/lib/ethers-v6/Exchange.js';
|
||||
import type { LibValidator } from '@orionprotocol/contracts/lib/ethers-v6/Exchange.js';
|
||||
import {
|
||||
UniswapV3Pool__factory, ERC20__factory,
|
||||
SwapExecutor__factory, CurveRegistry__factory
|
||||
ERC20__factory
|
||||
} from '@orionprotocol/contracts/lib/ethers-v6/index.js';
|
||||
import { ethers, type BigNumberish, type AddressLike, concat, type BytesLike } from 'ethers';
|
||||
import { ethers, type BigNumberish, type BytesLike, JsonRpcProvider } from 'ethers';
|
||||
import { safeGet, SafeArray } from '../../utils/safeGetters.js';
|
||||
import type Unit from '../index.js';
|
||||
import { simpleFetch } from 'simple-typed-fetch';
|
||||
import { BigNumber } from 'bignumber.js';
|
||||
import type Unit from '../index.js';
|
||||
import { generateUni2Calls, generateUni2Call } from './callGenerators/uniswapV2.js';
|
||||
import { generateUni3Calls, generateOrion3Calls, generateUni3Call, generateOrion3Call } from './callGenerators/uniswapV3.js';
|
||||
import { exchangeToNativeDecimals, generateCalls, pathCallWithBalance } from './callGenerators/utils.js';
|
||||
import { generateApproveCall, generateTransferCall } from './callGenerators/erc20.js';
|
||||
import { generateCurveStableSwapCall } from './callGenerators/curve.js';
|
||||
import type { SingleSwap } from '../../types.js';
|
||||
|
||||
const EXECUTOR_SWAP_FUNCTION = 'func_70LYiww'
|
||||
|
||||
export type SwapInfo = {
|
||||
pool: string
|
||||
assetIn: string
|
||||
assetOut: string
|
||||
factory: string
|
||||
}
|
||||
|
||||
export type CallParams = {
|
||||
isMandatory?: boolean
|
||||
target?: string
|
||||
gaslimit?: BigNumber
|
||||
value?: BigNumber
|
||||
}
|
||||
export type Factory = "UniswapV2" | "UniswapV3" | "Curve" | "OrionV2" | "OrionV3"
|
||||
|
||||
export type GenerateSwapCalldataParams = {
|
||||
amount: BigNumberish
|
||||
minReturnAmount: BigNumberish
|
||||
receiverAddress: string
|
||||
path: ArrayLike<SwapInfo>
|
||||
path: ArrayLike<SingleSwap>
|
||||
unit: Unit
|
||||
}
|
||||
|
||||
@@ -37,85 +27,124 @@ export default async function generateSwapCalldata({
|
||||
amount,
|
||||
minReturnAmount,
|
||||
receiverAddress,
|
||||
path: path_,
|
||||
path: arrayLikePath,
|
||||
unit
|
||||
}: GenerateSwapCalldataParams
|
||||
): Promise<{ calldata: string, swapDescription: ExchangeWithGenericSwap.SwapDescriptionStruct }> {
|
||||
if (path_ == undefined || path_.length == 0) {
|
||||
): Promise<{ calldata: string, swapDescription: LibValidator.SwapDescriptionStruct }> {
|
||||
if (arrayLikePath == undefined || arrayLikePath.length == 0) {
|
||||
throw new Error('Empty path');
|
||||
}
|
||||
const wethAddress = safeGet(unit.contracts, 'WETH')
|
||||
const curveRegistryAddress = safeGet(unit.contracts, 'curveRegistry')
|
||||
const { assetToAddress, swapExecutorContractAddress, exchangeContractAddress } = await simpleFetch(unit.blockchainService.getInfo)();
|
||||
let path = SafeArray.from(path_).map((swapInfo) => {
|
||||
let path = SafeArray.from(arrayLikePath).map((swapInfo) => {
|
||||
swapInfo.assetIn = assetToAddress[swapInfo.assetIn] ?? swapInfo.assetIn.toLowerCase();
|
||||
swapInfo.assetOut = assetToAddress[swapInfo.assetOut] ?? swapInfo.assetOut.toLowerCase();
|
||||
return swapInfo;
|
||||
})
|
||||
const factory = path.first().factory
|
||||
if (!path.every(swapInfo => swapInfo.factory === factory)) {
|
||||
throw new Error('Supporting only swaps with single factory');
|
||||
}
|
||||
const swapDescription: ExchangeWithGenericSwap.SwapDescriptionStruct = {
|
||||
srcToken: path.first().assetIn,
|
||||
dstToken: path.last().assetOut,
|
||||
srcReceiver: swapExecutorContractAddress ?? '',
|
||||
|
||||
const { factory, assetIn: srcToken } = path.first()
|
||||
const dstToken = path.last().assetOut
|
||||
|
||||
let swapDescription: LibValidator.SwapDescriptionStruct = {
|
||||
srcToken: srcToken,
|
||||
dstToken: dstToken,
|
||||
srcReceiver: swapExecutorContractAddress,
|
||||
dstReceiver: receiverAddress,
|
||||
amount,
|
||||
minReturnAmount,
|
||||
flags: 0
|
||||
}
|
||||
const amountNativeDecimals = await exchangeToNativeDecimals(srcToken, amount, unit.provider);
|
||||
|
||||
const exchangeToNativeDecimals = async (token: AddressLike) => {
|
||||
if (typeof token !== 'string' && 'getAddress' in token) {
|
||||
token = await token.getAddress();
|
||||
} else {
|
||||
token = await token
|
||||
}
|
||||
let decimals = 18n
|
||||
if (token !== ethers.ZeroAddress) {
|
||||
const contract = ERC20__factory.connect(token, unit.provider)
|
||||
decimals = await contract.decimals()
|
||||
}
|
||||
return BigNumber(amount.toString()).multipliedBy(BigNumber(10).pow(decimals.toString())).div(BigNumber(10).pow(8))
|
||||
}
|
||||
const amountNativeDecimals = await exchangeToNativeDecimals(swapDescription.srcToken);
|
||||
|
||||
path = SafeArray.from(path_).map((swapInfo) => {
|
||||
if (swapInfo.assetIn == ethers.ZeroAddress) swapInfo.assetIn = wethAddress
|
||||
if (swapInfo.assetOut == ethers.ZeroAddress) swapInfo.assetOut = wethAddress
|
||||
return swapInfo;
|
||||
path = SafeArray.from(arrayLikePath).map((singleSwap) => {
|
||||
if (singleSwap.assetIn == ethers.ZeroAddress) singleSwap.assetIn = wethAddress
|
||||
if (singleSwap.assetOut == ethers.ZeroAddress) singleSwap.assetOut = wethAddress
|
||||
return singleSwap;
|
||||
});
|
||||
const isSingleFactorySwap = path.every(singleSwap => singleSwap.factory === factory)
|
||||
let calldata: BytesLike
|
||||
if (isSingleFactorySwap) {
|
||||
({ swapDescription, calldata } = await processSingleFactorySwaps(
|
||||
factory,
|
||||
swapDescription,
|
||||
path,
|
||||
exchangeContractAddress,
|
||||
amountNativeDecimals,
|
||||
swapExecutorContractAddress,
|
||||
curveRegistryAddress,
|
||||
unit.provider
|
||||
))
|
||||
} else {
|
||||
({ swapDescription, calldata } = await processMultiFactorySwaps(
|
||||
swapDescription,
|
||||
path,
|
||||
exchangeContractAddress,
|
||||
amountNativeDecimals,
|
||||
swapExecutorContractAddress,
|
||||
curveRegistryAddress,
|
||||
unit.provider
|
||||
))
|
||||
}
|
||||
|
||||
let calldata: string
|
||||
return { swapDescription, calldata }
|
||||
}
|
||||
|
||||
async function processSingleFactorySwaps(
|
||||
factory: Factory,
|
||||
swapDescription: LibValidator.SwapDescriptionStruct,
|
||||
path: SafeArray<SingleSwap>,
|
||||
recipient: string,
|
||||
amount: BigNumberish,
|
||||
swapExecutorContractAddress: string,
|
||||
curveRegistryAddress: string,
|
||||
provider: JsonRpcProvider
|
||||
) {
|
||||
let calldata: BytesLike
|
||||
switch (factory) {
|
||||
case 'OrionV2': {
|
||||
swapDescription.srcReceiver = path.first().pool
|
||||
calldata = await generateUni2Calls(exchangeContractAddress, path);
|
||||
calldata = await generateUni2Calls(path, recipient);
|
||||
break;
|
||||
}
|
||||
case 'UniswapV2': {
|
||||
swapDescription.srcReceiver = path.first().pool
|
||||
calldata = await generateUni2Calls(exchangeContractAddress, path);
|
||||
calldata = await generateUni2Calls(path, recipient);
|
||||
break;
|
||||
}
|
||||
case 'UniswapV3': {
|
||||
calldata = await generateUni3Calls(amountNativeDecimals.toString(), exchangeContractAddress, path, unit.provider)
|
||||
calldata = await generateUni3Calls(path, amount, recipient, provider)
|
||||
break;
|
||||
}
|
||||
case 'OrionV3': {
|
||||
calldata = await generateOrion3Calls(amountNativeDecimals.toString(), exchangeContractAddress, path, unit.provider)
|
||||
calldata = await generateOrion3Calls(path, amount, recipient, provider)
|
||||
break;
|
||||
}
|
||||
case 'Curve': {
|
||||
calldata = await generateCurveStableSwapCalls(
|
||||
amountNativeDecimals.toString(),
|
||||
exchangeContractAddress,
|
||||
swapExecutorContractAddress ?? '',
|
||||
path,
|
||||
unit.provider,
|
||||
if (path.length > 1) {
|
||||
throw new Error('Supporting only single stable swap on curve')
|
||||
}
|
||||
const { pool, assetIn } = path.first()
|
||||
const firstToken = ERC20__factory.connect(assetIn, provider)
|
||||
const executorAllowance = await firstToken.allowance(swapExecutorContractAddress, pool)
|
||||
const calls: BytesLike[] = []
|
||||
if (executorAllowance <= BigInt(amount)) {
|
||||
const approveCall = await generateApproveCall(
|
||||
assetIn,
|
||||
pool,
|
||||
ethers.MaxUint256
|
||||
)
|
||||
calls.push(approveCall)
|
||||
}
|
||||
let curveCall = await generateCurveStableSwapCall(
|
||||
amount,
|
||||
recipient,
|
||||
path.first(),
|
||||
provider,
|
||||
curveRegistryAddress
|
||||
);
|
||||
calls.push(curveCall)
|
||||
calldata = await generateCalls(calls)
|
||||
break;
|
||||
}
|
||||
default: {
|
||||
@@ -125,174 +154,77 @@ export default async function generateSwapCalldata({
|
||||
return { swapDescription, calldata }
|
||||
}
|
||||
|
||||
export async function generateUni2Calls(
|
||||
exchangeAddress: string,
|
||||
path: SafeArray<SwapInfo>
|
||||
) {
|
||||
const executorInterface = SwapExecutor__factory.createInterface()
|
||||
const calls: BytesLike[] = []
|
||||
if (path.length > 1) {
|
||||
for (let i = 0; i < path.length - 1; ++i) {
|
||||
const currentSwap = path.get(i)
|
||||
const nextSwap = path.get(i + 1)
|
||||
|
||||
const calldata = executorInterface.encodeFunctionData('swapUniV2', [
|
||||
currentSwap.pool,
|
||||
currentSwap.assetIn,
|
||||
currentSwap.assetOut,
|
||||
ethers.AbiCoder.defaultAbiCoder().encode(['uint256'], [concat(['0x03', nextSwap.pool])]),
|
||||
]
|
||||
)
|
||||
calls.push(addCallParams(calldata))
|
||||
}
|
||||
}
|
||||
const lastSwap = path.last();
|
||||
const calldata = executorInterface.encodeFunctionData('swapUniV2', [
|
||||
lastSwap.pool,
|
||||
lastSwap.assetIn,
|
||||
lastSwap.assetOut,
|
||||
ethers.AbiCoder.defaultAbiCoder().encode(['uint256'], [concat(['0x03', exchangeAddress])]),
|
||||
])
|
||||
calls.push(addCallParams(calldata))
|
||||
|
||||
return await generateCalls(calls)
|
||||
}
|
||||
|
||||
async function generateUni3Calls(
|
||||
async function processMultiFactorySwaps(
|
||||
swapDescription: LibValidator.SwapDescriptionStruct,
|
||||
path: SafeArray<SingleSwap>,
|
||||
recipient: string,
|
||||
amount: BigNumberish,
|
||||
exchangeContractAddress: string,
|
||||
path: SafeArray<SwapInfo>,
|
||||
provider: ethers.JsonRpcApiProvider
|
||||
swapExecutorContractAddress: string,
|
||||
curveRegistryAddress: string,
|
||||
provider: JsonRpcProvider
|
||||
) {
|
||||
const encodedPools: string[] = []
|
||||
let calls: BytesLike[] = []
|
||||
for (const swap of path) {
|
||||
const pool = UniswapV3Pool__factory.connect(swap.pool, provider)
|
||||
const token0 = await pool.token0()
|
||||
const zeroForOne = token0.toLowerCase() === swap.assetIn.toLowerCase()
|
||||
const unwrapWETH = swap.assetOut === ethers.ZeroAddress
|
||||
|
||||
let encodedPool = ethers.solidityPacked(['uint256'], [await pool.getAddress()])
|
||||
encodedPool = ethers.dataSlice(encodedPool, 1)
|
||||
let firstByte = 0
|
||||
if (unwrapWETH) firstByte += 32
|
||||
if (!zeroForOne) firstByte += 128
|
||||
const encodedFirstByte = ethers.solidityPacked(['uint8'], [firstByte])
|
||||
encodedPool = ethers.hexlify(ethers.concat([encodedFirstByte, encodedPool]))
|
||||
encodedPools.push(encodedPool)
|
||||
}
|
||||
const executorInterface = SwapExecutor__factory.createInterface()
|
||||
let calldata = executorInterface.encodeFunctionData('uniswapV3SwapTo', [encodedPools, exchangeContractAddress, amount])
|
||||
calldata = addCallParams(calldata)
|
||||
|
||||
return await generateCalls([calldata])
|
||||
}
|
||||
|
||||
async function generateOrion3Calls(
|
||||
amount: BigNumberish,
|
||||
exchangeContractAddress: string,
|
||||
path: SafeArray<SwapInfo>,
|
||||
provider: ethers.JsonRpcApiProvider
|
||||
) {
|
||||
const encodedPools: string[] = []
|
||||
for (const swap of path) {
|
||||
const pool = UniswapV3Pool__factory.connect(swap.pool, provider)
|
||||
const token0 = await pool.token0()
|
||||
const zeroForOne = token0.toLowerCase() === swap.assetIn.toLowerCase()
|
||||
const unwrapWETH = swap.assetOut === ethers.ZeroAddress
|
||||
|
||||
let encodedPool = ethers.solidityPacked(['uint256'], [await pool.getAddress()])
|
||||
encodedPool = ethers.dataSlice(encodedPool, 1)
|
||||
let firstByte = 0
|
||||
if (unwrapWETH) firstByte += 32
|
||||
if (!zeroForOne) firstByte += 128
|
||||
const encodedFirstByte = ethers.solidityPacked(['uint8'], [firstByte])
|
||||
encodedPool = ethers.hexlify(ethers.concat([encodedFirstByte, encodedPool]))
|
||||
encodedPools.push(encodedPool)
|
||||
}
|
||||
const executorInterface = SwapExecutor__factory.createInterface()
|
||||
let calldata = executorInterface.encodeFunctionData('orionV3SwapTo', [encodedPools, exchangeContractAddress, amount])
|
||||
calldata = addCallParams(calldata)
|
||||
|
||||
return await generateCalls([calldata])
|
||||
}
|
||||
|
||||
async function generateCurveStableSwapCalls(
|
||||
amount: BigNumberish,
|
||||
exchangeContractAddress: string,
|
||||
executorAddress: string,
|
||||
path: SafeArray<SwapInfo>,
|
||||
provider: ethers.JsonRpcProvider,
|
||||
curveRegistry: string
|
||||
) {
|
||||
if (path.length > 1) {
|
||||
throw new Error('Supporting only single stable swap on curve')
|
||||
}
|
||||
const executorInterface = SwapExecutor__factory.createInterface()
|
||||
const registry = CurveRegistry__factory.connect(curveRegistry, provider)
|
||||
|
||||
const swap = path.first()
|
||||
const firstToken = ERC20__factory.connect(swap.assetIn, provider)
|
||||
const { pool, assetIn, assetOut } = swap
|
||||
const [i, j,] = await registry.get_coin_indices(pool, assetIn, assetOut)
|
||||
|
||||
const executorAllowance = await firstToken.allowance(executorAddress, swap.pool)
|
||||
const calls: BytesLike[] = []
|
||||
if (executorAllowance < BigInt(amount)) {
|
||||
const calldata = addCallParams(
|
||||
executorInterface.encodeFunctionData('safeApprove', [
|
||||
swap.assetIn,
|
||||
swap.pool,
|
||||
ethers.MaxUint256
|
||||
])
|
||||
)
|
||||
calls.push(calldata)
|
||||
}
|
||||
let calldata = executorInterface.encodeFunctionData('curveSwapStableAmountIn', [
|
||||
pool,
|
||||
assetOut,
|
||||
i,
|
||||
j,
|
||||
amount,
|
||||
0,
|
||||
exchangeContractAddress])
|
||||
|
||||
calldata = addCallParams(calldata)
|
||||
calls.push(calldata)
|
||||
|
||||
return await generateCalls(calls)
|
||||
}
|
||||
|
||||
// Adds additional byte to single swap with settings
|
||||
function addCallParams(
|
||||
calldata: BytesLike,
|
||||
callParams?: CallParams
|
||||
) {
|
||||
let firstByte = 0
|
||||
if (callParams) {
|
||||
if (callParams.value !== undefined) {
|
||||
firstByte += 16 // 00010000
|
||||
const encodedValue = ethers.solidityPacked(['uint128'], [callParams.value])
|
||||
calldata = ethers.hexlify(ethers.concat([encodedValue, calldata]))
|
||||
switch (swap.factory) {
|
||||
case 'OrionV2': {
|
||||
let transferCall = await generateTransferCall(swap.assetIn, swap.pool, 0)
|
||||
transferCall = pathCallWithBalance(transferCall, swap.assetIn)
|
||||
const uni2Call = await generateUni2Call(swap.pool, swap.assetIn, swap.assetOut, swapExecutorContractAddress)
|
||||
calls = calls.concat([transferCall, uni2Call])
|
||||
break;
|
||||
}
|
||||
case 'UniswapV2': {
|
||||
let transferCall = await generateTransferCall(swap.assetIn, swap.pool, 0)
|
||||
transferCall = pathCallWithBalance(transferCall, swap.assetIn)
|
||||
const uni2Call = await generateUni2Call(swap.pool, swap.assetIn, swap.assetOut, swapExecutorContractAddress)
|
||||
calls = calls.concat([transferCall, uni2Call])
|
||||
break;
|
||||
}
|
||||
case 'UniswapV3': {
|
||||
let uni3Call = await generateUni3Call(swap, 0, swapExecutorContractAddress, provider)
|
||||
uni3Call = pathCallWithBalance(uni3Call, swap.assetIn)
|
||||
calls.push(uni3Call)
|
||||
break;
|
||||
}
|
||||
case 'OrionV3': {
|
||||
let orion3Call = await generateOrion3Call(swap, 0, swapExecutorContractAddress, provider)
|
||||
orion3Call = pathCallWithBalance(orion3Call, swap.assetIn)
|
||||
calls.push(orion3Call)
|
||||
break;
|
||||
}
|
||||
case 'Curve': {
|
||||
const { pool, assetIn } = swap
|
||||
const firstToken = ERC20__factory.connect(assetIn, provider)
|
||||
const executorAllowance = await firstToken.allowance(swapExecutorContractAddress, pool)
|
||||
if (executorAllowance <= BigInt(amount)) {
|
||||
const approveCall = await generateApproveCall(
|
||||
assetIn,
|
||||
pool,
|
||||
ethers.MaxUint256
|
||||
)
|
||||
calls.push(approveCall)
|
||||
}
|
||||
let curveCall = await generateCurveStableSwapCall(
|
||||
amount,
|
||||
swapExecutorContractAddress,
|
||||
swap,
|
||||
provider,
|
||||
curveRegistryAddress
|
||||
);
|
||||
curveCall = pathCallWithBalance(curveCall, swap.assetIn)
|
||||
calls.push(curveCall)
|
||||
break;
|
||||
}
|
||||
default: {
|
||||
throw new Error(`Factory ${swap.factory} is not supported`)
|
||||
}
|
||||
}
|
||||
if (callParams.target !== undefined) {
|
||||
firstByte += 32 // 00100000
|
||||
const encodedAddress = ethers.solidityPacked(['address'], [callParams.target])
|
||||
calldata = ethers.hexlify(ethers.concat([encodedAddress, calldata]))
|
||||
}
|
||||
if (callParams.gaslimit !== undefined) {
|
||||
firstByte += 64 // 01000000
|
||||
const encodedGaslimit = ethers.solidityPacked(['uint32'], [callParams.gaslimit])
|
||||
calldata = ethers.hexlify(ethers.concat([encodedGaslimit, calldata]))
|
||||
}
|
||||
if (callParams.isMandatory !== undefined) firstByte += 128 // 10000000
|
||||
}
|
||||
const dstToken = swapDescription.dstToken
|
||||
let finalTransferCall = await generateTransferCall(dstToken, recipient, 0)
|
||||
finalTransferCall = pathCallWithBalance(finalTransferCall, dstToken)
|
||||
calls.push(finalTransferCall)
|
||||
const calldata = generateCalls(calls)
|
||||
|
||||
const encodedFirstByte = ethers.solidityPacked(['uint8'], [firstByte])
|
||||
calldata = ethers.hexlify(ethers.concat([encodedFirstByte, calldata]))
|
||||
return calldata
|
||||
}
|
||||
|
||||
function generateCalls(calls: BytesLike[]) {
|
||||
const executorInterface = SwapExecutor__factory.createInterface()
|
||||
return '0x' + executorInterface.encodeFunctionData(EXECUTOR_SWAP_FUNCTION, [ethers.ZeroAddress, calls]).slice(74)
|
||||
return { swapDescription, calldata }
|
||||
}
|
||||
|
||||
@@ -2,12 +2,8 @@ import type Unit from '../index.js';
|
||||
import deposit, { type DepositParams } from './deposit.js';
|
||||
import getSwapInfo, { type GetSwapInfoParams } from './getSwapInfo.js';
|
||||
import generateSwapCalldata, { type GenerateSwapCalldataParams } from './generateSwapCalldata.js';
|
||||
import swapLimit, {type SwapLimitParams} from './swapLimit.js';
|
||||
import swapMarket, { type SwapMarketParams } from './swapMarket.js';
|
||||
import withdraw, { type WithdrawParams } from './withdraw.js';
|
||||
|
||||
type PureSwapMarketParams = Omit<SwapMarketParams, 'unit'>
|
||||
type PureSwapLimitParams = Omit<SwapLimitParams, 'unit'>
|
||||
type PureDepositParams = Omit<DepositParams, 'unit'>
|
||||
type PureWithdrawParams = Omit<WithdrawParams, 'unit'>
|
||||
type PureGetSwapMarketInfoParams = Omit<GetSwapInfoParams, 'blockchainService' | 'aggregator'>
|
||||
@@ -20,20 +16,6 @@ export default class Exchange {
|
||||
this.unit = unit;
|
||||
}
|
||||
|
||||
public swapLimit(params: PureSwapLimitParams) {
|
||||
return swapLimit({
|
||||
...params,
|
||||
unit: this.unit,
|
||||
});
|
||||
}
|
||||
|
||||
public swapMarket(params: PureSwapMarketParams) {
|
||||
return swapMarket({
|
||||
...params,
|
||||
unit: this.unit,
|
||||
});
|
||||
}
|
||||
|
||||
public getSwapInfo(params: PureGetSwapMarketInfoParams) {
|
||||
return getSwapInfo({
|
||||
aggregator: this.unit.aggregator,
|
||||
|
||||
1
src/constants/factories.ts
Normal file
1
src/constants/factories.ts
Normal file
@@ -0,0 +1 @@
|
||||
export default ["UniswapV2", "UniswapV3", "Curve", "OrionV2", "OrionV3"] as const
|
||||
@@ -4,6 +4,7 @@ BigNumber.config({ EXPONENTIAL_AT: 1e+9 });
|
||||
export * as config from './config/index.js';
|
||||
export { default as Unit } from './Unit/index.js';
|
||||
export { default as Orion } from './Orion/index.js';
|
||||
export { default as factories} from './constants/factories.js';
|
||||
export * as utils from './utils/index.js';
|
||||
export * as services from './services/index.js';
|
||||
export * as crypt from './crypt/index.js';
|
||||
|
||||
@@ -17,8 +17,6 @@ import unsubscriptionDoneSchema from './schemas/unsubscriptionDoneSchema.js';
|
||||
import assetPairConfigSchema from './schemas/assetPairConfigSchema.js';
|
||||
import type { fullOrderSchema, orderUpdateSchema } from './schemas/addressUpdateSchema.js';
|
||||
import { objectKeys } from '../../../utils/objectKeys.js';
|
||||
// import assertError from '../../../utils/assertError.js';
|
||||
// import errorSchema from './schemas/errorSchema';
|
||||
|
||||
const UNSUBSCRIBE = 'u';
|
||||
const SERVER_PING_INTERVAL = 30000;
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { z } from 'zod';
|
||||
import MessageType from '../MessageType.js';
|
||||
import baseMessageSchema from './baseMessageSchema.js';
|
||||
import factories from '../../../../constants/factories.js';
|
||||
|
||||
const alternativeSchema = z.object({ // execution alternatives
|
||||
e: z.string().array(), // exchanges
|
||||
@@ -11,6 +12,7 @@ const alternativeSchema = z.object({ // execution alternatives
|
||||
aa: z.number().optional(), // available amount in
|
||||
aao: z.number().optional(), // available amount out
|
||||
});
|
||||
const factorySchema = z.enum(factories);
|
||||
const swapInfoSchemaBase = baseMessageSchema.extend({
|
||||
T: z.literal(MessageType.SWAP_INFO),
|
||||
S: z.string(), // swap request id
|
||||
@@ -37,7 +39,7 @@ const swapInfoSchemaBase = baseMessageSchema.extend({
|
||||
p: z.string(), // pool address
|
||||
ai: z.string().toUpperCase(), // asset in
|
||||
ao: z.string().toUpperCase(), // asset out
|
||||
f: z.string(), // factory
|
||||
f: factorySchema, // factory
|
||||
}))
|
||||
});
|
||||
|
||||
|
||||
@@ -11,7 +11,7 @@ const infoSchema = z.object({
|
||||
chainId: z.number(),
|
||||
chainName: z.string(),
|
||||
exchangeContractAddress: z.string(),
|
||||
swapExecutorContractAddress: z.string().optional(),
|
||||
swapExecutorContractAddress: z.string(),
|
||||
oracleContractAddress: z.string(),
|
||||
matcherAddress: z.string(),
|
||||
orderFeePercent: z.number(),
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
/* eslint-disable @typescript-eslint/consistent-type-definitions */
|
||||
import factories from './constants/factories.js';
|
||||
import type { BigNumber } from 'bignumber.js';
|
||||
import type subOrderStatuses from './constants/subOrderStatuses.js';
|
||||
import type positionStatuses from './constants/positionStatuses.js';
|
||||
@@ -165,11 +166,13 @@ export type SwapInfoAlternative = {
|
||||
availableAmountOut?: number | undefined
|
||||
}
|
||||
|
||||
type ExchangeContractPath = {
|
||||
export type Factory = typeof factories[number]
|
||||
|
||||
export type SingleSwap = {
|
||||
pool: string
|
||||
assetIn: string
|
||||
assetOut: string
|
||||
factory: string
|
||||
factory: Factory
|
||||
}
|
||||
|
||||
export type SwapInfoBase = {
|
||||
@@ -182,7 +185,7 @@ export type SwapInfoBase = {
|
||||
minAmountOut: number
|
||||
|
||||
path: string[]
|
||||
exchangeContractPath: ExchangeContractPath[]
|
||||
exchangeContractPath: SingleSwap[]
|
||||
exchanges?: string[] | undefined
|
||||
poolOptimal: boolean
|
||||
|
||||
|
||||
Reference in New Issue
Block a user