Merged with main

This commit is contained in:
lomonoshka
2023-10-10 19:03:38 +04:00
70 changed files with 9828 additions and 753 deletions

View File

@@ -1,5 +1,5 @@
import { SwapExecutor__factory, CurveRegistry__factory } from "@orionprotocol/contracts/lib/ethers-v5/index.js"
import type { BigNumberish, providers } from "ethers"
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"
@@ -7,7 +7,7 @@ export async function generateCurveStableSwapCall(
amount: BigNumberish,
to: string,
swap: SingleSwap,
provider: providers.JsonRpcProvider,
provider: JsonRpcProvider,
curveRegistry: string
) {
const executorInterface = SwapExecutor__factory.createInterface()

View File

@@ -1,13 +1,15 @@
import { SwapExecutor__factory } from "@orionprotocol/contracts/lib/ethers-v5/index.js"
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: string,
target: string,
token: AddressLike,
target: AddressLike,
amount: BigNumberish,
callParams?: CallParams
) {
const executorInterface = SwapExecutor__factory.createInterface()
const calldata = executorInterface.encodeFunctionData('safeTransfer', [
token,
@@ -19,8 +21,8 @@ export async function generateTransferCall(
}
export async function generateApproveCall(
token: string,
target: string,
token: AddressLike,
target: AddressLike,
amount: BigNumberish,
callParams?: CallParams
) {

View File

@@ -1,8 +1,6 @@
import { SwapExecutor__factory } from "@orionprotocol/contracts/lib/ethers-v5/index.js"
import { SafeArray } from "../../../utils/safeGetters.js"
import { BigNumber } from "ethers"
import type { BytesLike, BigNumberish } from "ethers"
import { defaultAbiCoder, concat } from "ethers/lib/utils.js"
import { type BytesLike, type BigNumberish, concat, ethers, toBeHex } from "ethers"
import { addCallParams, generateCalls } from "./utils.js"
import type { SingleSwap } from "../../../types.js"
@@ -31,7 +29,7 @@ export async function generateUni2Calls(
lastSwap.pool,
lastSwap.assetIn,
lastSwap.assetOut,
defaultAbiCoder.encode(['uint256'], [concat(['0x03', recipient])]),
ethers.AbiCoder.defaultAbiCoder().encode(['uint256'], [concat(['0x03', recipient])]),
])
calls.push(addCallParams(calldata))
@@ -43,14 +41,14 @@ export async function generateUni2Call(
assetIn: string,
assetOut: string,
recipient: string,
fee: BigNumberish = BigNumber.from(3),
fee: BigNumberish = 3,
) {
const executorInterface = SwapExecutor__factory.createInterface()
const calldata = executorInterface.encodeFunctionData('swapUniV2', [
pool,
assetIn,
assetOut,
defaultAbiCoder.encode(['uint256'], [concat([BigNumber.from(fee).toHexString(), recipient])]),
ethers.AbiCoder.defaultAbiCoder().encode(['uint256'], [concat([toBeHex(fee), recipient])]),
])
return addCallParams(calldata)
}

View File

@@ -1,5 +1,5 @@
import { SwapExecutor__factory, UniswapV3Pool__factory } from "@orionprotocol/contracts/lib/ethers-v5/index.js"
import { type BigNumberish, providers, type BytesLike, ethers } from "ethers"
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"
@@ -8,7 +8,7 @@ export async function generateUni3Call(
swap: SingleSwap,
amount: BigNumberish | undefined,
recipient: string,
provider: providers.JsonRpcProvider
provider: JsonRpcProvider
) {
if (typeof amount === 'undefined') amount = 0
@@ -23,7 +23,7 @@ export async function generateOrion3Call(
swap: SingleSwap,
amount: BigNumberish | undefined,
recipient: string,
provider: providers.JsonRpcProvider
provider: JsonRpcProvider
) {
if (typeof amount === 'undefined') amount = 0
@@ -38,9 +38,9 @@ export async function generateUni3Calls(
path: SafeArray<SingleSwap>,
amount: BigNumberish,
recipient: string,
provider: providers.JsonRpcProvider
provider: JsonRpcProvider
) {
const encodedPools: BytesLike[] = []
const encodedPools: BigNumberish[] = []
for (const swap of path) {
const encodedPool = await encodePoolV3(swap.pool, swap.assetIn, swap.assetOut, provider)
encodedPools.push(encodedPool)
@@ -56,9 +56,9 @@ export async function generateOrion3Calls(
path: SafeArray<SingleSwap>,
amount: BigNumberish,
recipient: string,
provider: providers.JsonRpcProvider
provider: JsonRpcProvider
) {
const encodedPools: BytesLike[] = []
const encodedPools: BigNumberish[] = []
for (const swap of path) {
const encodedPool = await encodePoolV3(swap.pool, swap.assetIn, swap.assetOut, provider)
encodedPools.push(encodedPool)
@@ -74,19 +74,19 @@ export async function encodePoolV3(
poolAddress: string,
assetInAddress: string,
assetOutAddress: string,
provider: providers.JsonRpcProvider
provider: JsonRpcProvider
) {
const pool = UniswapV3Pool__factory.connect(poolAddress, provider)
const token0 = await pool.token0()
const zeroForOne = token0.toLowerCase() === assetInAddress.toLowerCase()
const unwrapWETH = assetOutAddress === ethers.constants.AddressZero
const unwrapWETH = assetOutAddress === ethers.ZeroAddress
let encodedPool = ethers.utils.solidityPack(['uint256'], [pool.address])
encodedPool = ethers.utils.hexDataSlice(encodedPool, 1)
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.utils.solidityPack(['uint8'], [firstByte])
encodedPool = ethers.utils.hexlify(ethers.utils.concat([encodedFirstByte, encodedPool]))
const encodedFirstByte = ethers.solidityPacked(['uint8'], [firstByte])
encodedPool = ethers.hexlify(ethers.concat([encodedFirstByte, encodedPool]))
return encodedPool
}

View File

@@ -1,14 +1,14 @@
import type { PromiseOrValue } from "@orionprotocol/contracts/lib/ethers-v5/common.js"
import { ERC20__factory, SwapExecutor__factory } from "@orionprotocol/contracts/lib/ethers-v5/index.js"
import { type BytesLike, ethers, BigNumber, type BigNumberish, providers } from "ethers"
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?: BigNumber,
value?: BigNumber
gaslimit?: BigNumberish,
value?: BigNumberish
}
export type PatchParams = {
@@ -19,7 +19,7 @@ export type PatchParams = {
export function pathCallWithBalance(
calldata: BytesLike,
tokenAddress: string,
tokenAddress: AddressLike,
patchParams: PatchParams = { skipCallDataPatching: false, skipValuePatching: true }
) {
const executorInterface = SwapExecutor__factory.createInterface()
@@ -28,7 +28,7 @@ export function pathCallWithBalance(
calldata,
skipMaskAndOffset,
tokenAddress,
ethers.constants.MaxUint256])
ethers.MaxUint256])
return addCallParams(calldata)
}
@@ -40,31 +40,31 @@ export function addCallParams(
if (callParams) {
if (callParams.value !== undefined) {
firstByte += 16 // 00010000
const encodedValue = ethers.utils.solidityPack(['uint128'], [callParams.value])
calldata = ethers.utils.hexlify(ethers.utils.concat([encodedValue, calldata]))
const encodedValue = ethers.solidityPacked(['uint128'], [callParams.value])
calldata = ethers.hexlify(ethers.concat([encodedValue, calldata]))
}
if (callParams.target !== undefined) {
firstByte += 32 // 00100000
const encodedAddress = ethers.utils.solidityPack(['address'], [callParams.target])
calldata = ethers.utils.hexlify(ethers.utils.concat([encodedAddress, calldata]))
const encodedAddress = ethers.solidityPacked(['address'], [callParams.target])
calldata = ethers.hexlify(ethers.concat([encodedAddress, calldata]))
}
if (callParams.gaslimit !== undefined) {
firstByte += 64 // 01000000
const encodedGaslimit = ethers.utils.solidityPack(['uint32'], [callParams.gaslimit])
calldata = ethers.utils.hexlify(ethers.utils.concat([encodedGaslimit, calldata]))
const encodedGaslimit = ethers.solidityPacked(['uint32'], [callParams.gaslimit])
calldata = ethers.hexlify(ethers.concat([encodedGaslimit, calldata]))
}
if (callParams.isMandatory !== undefined) firstByte += 128 // 10000000
}
const encodedFirstByte = ethers.utils.solidityPack(['uint8'], [firstByte])
calldata = ethers.utils.hexlify(ethers.utils.concat([encodedFirstByte, calldata]))
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.utils.solidityPack(["uint256"], [(calldata.length - 4) / 2 - 32])
mask = ethers.utils.hexDataSlice(mask, 1)
let mask = ethers.solidityPacked(["uint256"], [(calldata.length - 4) / 2 - 32])
mask = ethers.dataSlice(mask, 1)
if (patchParams) {
if (patchParams.skipOnZeroAmount !== undefined && patchParams.skipOnZeroAmount === false) {
firstByte += 32
@@ -79,23 +79,25 @@ export function createPatchMask(calldata: BytesLike, patchParams?: PatchParams)
console.log(firstByte)
}
}
const encodedFirstByte = ethers.utils.solidityPack(["uint8"], [firstByte])
mask = ethers.utils.hexlify(ethers.utils.concat([encodedFirstByte, mask]))
const encodedFirstByte = ethers.solidityPacked(["uint8"], [firstByte])
mask = ethers.hexlify(ethers.concat([encodedFirstByte, mask]))
console.log(mask)
return mask
}
export function generateCalls(calls: BytesLike[]) {
const executorInterface = SwapExecutor__factory.createInterface()
return '0x' + executorInterface.encodeFunctionData(EXECUTOR_SWAP_FUNCTION, [ethers.constants.AddressZero, calls]).slice(74)
return '0x' + executorInterface.encodeFunctionData(EXECUTOR_SWAP_FUNCTION, [ethers.ZeroAddress, calls]).slice(74)
}
export async function exchangeToNativeDecimals(token: PromiseOrValue<string>, amount: BigNumberish, provider: providers.JsonRpcProvider) {
export async function exchangeToNativeDecimals(token: AddressLike, amount: BigNumberish, provider: ethers.JsonRpcProvider) {
token = await token
let decimals = 18
if (token !== ethers.constants.AddressZero) {
if (typeof token !== "string") token = await token.getAddress()
let decimals = 18n
if (token !== ethers.ZeroAddress) {
const contract = ERC20__factory.connect(token, provider)
decimals = await contract.decimals()
decimals = BigInt(await contract.decimals())
}
return BigNumber.from(amount).mul(BigNumber.from(10).pow(decimals)).div(BigNumber.from(10).pow(8))
return BigInt(amount) * (BigInt(10) ** decimals) / (BigInt(10) ** 8n)
}

View File

@@ -1,6 +1,6 @@
import { BigNumber } from 'bignumber.js';
import { ethers } from 'ethers';
import { Exchange__factory } from '@orionprotocol/contracts/lib/ethers-v5/index.js';
import { Exchange__factory } from '@orionprotocol/contracts/lib/ethers-v6/index.js';
import getBalances from '../../utils/getBalances.js';
import BalanceGuard from '../../BalanceGuard.js';
import type Unit from '../index.js';
@@ -51,7 +51,7 @@ export default async function deposit({
const balances = await getBalances(
{
[asset]: assetAddress,
[nativeCryptocurrency]: ethers.constants.AddressZero,
[nativeCryptocurrency]: ethers.ZeroAddress,
},
aggregator,
walletAddress,
@@ -63,7 +63,7 @@ export default async function deposit({
balances,
{
name: nativeCryptocurrency,
address: ethers.constants.AddressZero,
address: ethers.ZeroAddress,
},
provider,
signer,
@@ -80,34 +80,34 @@ export default async function deposit({
sources: ['wallet'],
});
let unsignedTx: ethers.PopulatedTransaction;
let unsignedTx: ethers.TransactionLike;
if (asset === nativeCryptocurrency) {
unsignedTx = await exchangeContract.populateTransaction.deposit();
unsignedTx = await exchangeContract.deposit.populateTransaction();
unsignedTx.value = normalizeNumber(amount, NATIVE_CURRENCY_PRECISION, BigNumber.ROUND_CEIL);
unsignedTx.gasLimit = ethers.BigNumber.from(DEPOSIT_ETH_GAS_LIMIT);
unsignedTx.gasLimit = BigInt(DEPOSIT_ETH_GAS_LIMIT);
} else {
unsignedTx = await exchangeContract.populateTransaction.depositAsset(
unsignedTx = await exchangeContract.depositAsset.populateTransaction(
assetAddress,
normalizeNumber(amount, INTERNAL_PROTOCOL_PRECISION, BigNumber.ROUND_CEIL),
);
unsignedTx.gasLimit = ethers.BigNumber.from(DEPOSIT_ERC20_GAS_LIMIT);
unsignedTx.gasLimit = BigInt(DEPOSIT_ERC20_GAS_LIMIT);
}
const transactionCost = ethers.BigNumber.from(unsignedTx.gasLimit).mul(gasPriceWei);
const denormalizedTransactionCost = denormalizeNumber(transactionCost, NATIVE_CURRENCY_PRECISION);
const transactionCost = BigInt(unsignedTx.gasLimit) * BigInt(gasPriceWei);
const denormalizedTransactionCost = denormalizeNumber(transactionCost, BigInt(NATIVE_CURRENCY_PRECISION));
balanceGuard.registerRequirement({
reason: 'Network fee',
asset: {
name: nativeCryptocurrency,
address: ethers.constants.AddressZero,
address: ethers.ZeroAddress,
},
amount: denormalizedTransactionCost.toString(),
sources: ['wallet'],
});
unsignedTx.chainId = parseInt(chainId, 10);
unsignedTx.gasPrice = ethers.BigNumber.from(gasPriceWei);
unsignedTx.gasPrice = BigInt(gasPriceWei);
unsignedTx.from = walletAddress;
await balanceGuard.check(true);
@@ -117,10 +117,10 @@ export default async function deposit({
const signedTx = await signer.signTransaction(unsignedTx);
try {
const txResponse = await provider.sendTransaction(signedTx);
const txResponse = await provider.broadcastTransaction(signedTx);
console.log(`Deposit tx sent: ${txResponse.hash}. Waiting for confirmation...`);
const txReceipt = await txResponse.wait();
if (txReceipt.status !== undefined) {
if (txReceipt?.status !== undefined) {
console.log('Deposit tx confirmed');
} else {
console.log('Deposit tx failed');

View File

@@ -1,6 +1,8 @@
import type { ExchangeWithGenericSwap } from '@orionprotocol/contracts/lib/ethers-v5/Exchange.js';
import { ERC20__factory } from '@orionprotocol/contracts/lib/ethers-v5/index.js';
import { type BytesLike, ethers, type BigNumberish, providers } from 'ethers';
import type { LibValidator } from '@orionprotocol/contracts/lib/ethers-v6/Exchange.js';
import {
ERC20__factory
} from '@orionprotocol/contracts/lib/ethers-v6/index.js';
import { ethers, type BigNumberish, type BytesLike, JsonRpcProvider } from 'ethers';
import { safeGet, SafeArray } from '../../utils/safeGetters.js';
import { simpleFetch } from 'simple-typed-fetch';
import type Unit from '../index.js';
@@ -13,8 +15,6 @@ import type { SingleSwap } from '../../types.js';
export type Factory = "UniswapV2" | "UniswapV3" | "Curve" | "OrionV2" | "OrionV3"
export type GenerateSwapCalldataParams = {
amount: BigNumberish
minReturnAmount: BigNumberish
@@ -30,23 +30,23 @@ export default async function generateSwapCalldata({
path: arrayLikePath,
unit
}: GenerateSwapCalldataParams
): Promise<{ calldata: string, swapDescription: ExchangeWithGenericSwap.SwapDescriptionStruct }> {
): 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(arrayLikePath).map((singleSwap) => {
singleSwap.assetIn = safeGet(assetToAddress, singleSwap.assetIn);
singleSwap.assetOut = safeGet(assetToAddress, singleSwap.assetOut);
return singleSwap;
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, assetIn: srcToken } = path.first()
const dstToken = path.last().assetOut
let swapDescription: ExchangeWithGenericSwap.SwapDescriptionStruct = {
let swapDescription: LibValidator.SwapDescriptionStruct = {
srcToken: srcToken,
dstToken: dstToken,
srcReceiver: swapExecutorContractAddress,
@@ -58,8 +58,8 @@ export default async function generateSwapCalldata({
const amountNativeDecimals = await exchangeToNativeDecimals(srcToken, amount, unit.provider);
path = SafeArray.from(arrayLikePath).map((singleSwap) => {
if (singleSwap.assetIn == ethers.constants.AddressZero) singleSwap.assetIn = wethAddress
if (singleSwap.assetOut == ethers.constants.AddressZero) singleSwap.assetOut = wethAddress
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)
@@ -92,13 +92,13 @@ export default async function generateSwapCalldata({
async function processSingleFactorySwaps(
factory: Factory,
swapDescription: ExchangeWithGenericSwap.SwapDescriptionStruct,
swapDescription: LibValidator.SwapDescriptionStruct,
path: SafeArray<SingleSwap>,
recipient: string,
amount: BigNumberish,
swapExecutorContractAddress: string,
curveRegistryAddress: string,
provider: providers.JsonRpcProvider
provider: JsonRpcProvider
) {
let calldata: BytesLike
switch (factory) {
@@ -128,12 +128,12 @@ async function processSingleFactorySwaps(
const firstToken = ERC20__factory.connect(assetIn, provider)
const executorAllowance = await firstToken.allowance(swapExecutorContractAddress, pool)
const calls: BytesLike[] = []
if (executorAllowance.lt(amount)) {
const approveCall = await generateApproveCall(
assetIn,
pool,
ethers.constants.MaxUint256
)
if (executorAllowance <= BigInt(amount)) {
const approveCall = await generateApproveCall(
assetIn,
pool,
ethers.MaxUint256
)
calls.push(approveCall)
}
let curveCall = await generateCurveStableSwapCall(
@@ -155,13 +155,13 @@ async function processSingleFactorySwaps(
}
async function processMultiFactorySwaps(
swapDescription: ExchangeWithGenericSwap.SwapDescriptionStruct,
swapDescription: LibValidator.SwapDescriptionStruct,
path: SafeArray<SingleSwap>,
recipient: string,
amount: BigNumberish,
swapExecutorContractAddress: string,
curveRegistryAddress: string,
provider: providers.JsonRpcProvider
provider: JsonRpcProvider
) {
let calls: BytesLike[] = []
for (const swap of path) {
@@ -196,12 +196,12 @@ async function processMultiFactorySwaps(
const { pool, assetIn } = swap
const firstToken = ERC20__factory.connect(assetIn, provider)
const executorAllowance = await firstToken.allowance(swapExecutorContractAddress, pool)
if (executorAllowance.lt(amount)) {
const approveCall = await generateApproveCall(
assetIn,
pool,
ethers.constants.MaxUint256
)
if (executorAllowance <= BigInt(amount)) {
const approveCall = await generateApproveCall(
assetIn,
pool,
ethers.MaxUint256
)
calls.push(approveCall)
}
let curveCall = await generateCurveStableSwapCall(
@@ -220,11 +220,11 @@ async function processMultiFactorySwaps(
}
}
}
const dstToken = await swapDescription.dstToken
const dstToken = swapDescription.dstToken
let finalTransferCall = await generateTransferCall(dstToken, recipient, 0)
finalTransferCall = pathCallWithBalance(finalTransferCall, dstToken)
calls.push(finalTransferCall)
const calldata = await generateCalls(calls)
const calldata = generateCalls(calls)
return { swapDescription, calldata }
}
}

View File

@@ -51,7 +51,7 @@ export default async function getSwapInfo({
const allPrices = await simpleFetch(blockchainService.getPricesWithQuoteAsset)();
const gasPriceWei = await simpleFetch(blockchainService.getGasPriceWei)();
const gasPriceGwei = ethers.utils.formatUnits(gasPriceWei, 'gwei').toString();
const gasPriceGwei = ethers.formatUnits(gasPriceWei, 'gwei').toString();
const assetInAddress = assetToAddress[assetIn];
if (assetInAddress === undefined) throw new Error(`Asset '${assetIn}' not found`);
@@ -101,15 +101,15 @@ export default async function getSwapInfo({
}
if (route === 'pool') {
const transactionCost = ethers.BigNumber.from(SWAP_THROUGH_ORION_POOL_GAS_LIMIT).mul(gasPriceWei);
const denormalizedTransactionCost = denormalizeNumber(transactionCost, NATIVE_CURRENCY_PRECISION);
const transactionCost = BigInt(SWAP_THROUGH_ORION_POOL_GAS_LIMIT) * BigInt(gasPriceWei);
const denormalizedTransactionCost = denormalizeNumber(transactionCost, BigInt(NATIVE_CURRENCY_PRECISION));
return {
route,
swapInfo,
fee: {
assetName: nativeCryptocurrencyName,
assetAddress: ethers.constants.AddressZero,
assetAddress: ethers.ZeroAddress,
networkFeeInFeeAsset: denormalizedTransactionCost.toString(),
protocolFeeInFeeAsset: undefined,
},
@@ -134,7 +134,7 @@ export default async function getSwapInfo({
gasPriceGwei,
feePercent,
baseAssetAddress,
ethers.constants.AddressZero,
ethers.ZeroAddress,
feeAssetAddress,
allPrices.prices
);

View File

@@ -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,

View File

@@ -1,6 +1,6 @@
import { BigNumber } from 'bignumber.js';
import { ethers } from 'ethers';
import { Exchange__factory } from '@orionprotocol/contracts/lib/ethers-v5/index.js';
import { Exchange__factory } from '@orionprotocol/contracts/lib/ethers-v6/index.js';
import getBalances from '../../utils/getBalances.js';
import BalanceGuard from '../../BalanceGuard.js';
import getAvailableSources from '../../utils/getAvailableFundsSources.js';
@@ -44,7 +44,7 @@ type PoolSwap = {
amountOut: number
through: 'pool'
txHash: string
wait: (confirmations?: number | undefined) => Promise<ethers.providers.TransactionReceipt>
wait: (confirmations?: number | undefined) => Promise<ethers.TransactionReceipt | null>
}
export type Swap = AggregatorOrder | PoolSwap;
@@ -95,7 +95,7 @@ export default async function swapLimit({
const { factories } = await simpleFetch(blockchainService.getPoolsConfig)();
const poolExchangesList = factories !== undefined ? Object.keys(factories) : [];
const gasPriceGwei = ethers.utils.formatUnits(gasPriceWei, 'gwei').toString();
const gasPriceGwei = ethers.formatUnits(gasPriceWei, 'gwei').toString();
const assetInAddress = assetToAddress[assetIn];
if (assetInAddress === undefined) throw new Error(`Asset '${assetIn}' not found`);
@@ -108,7 +108,7 @@ export default async function swapLimit({
{
[assetIn]: assetInAddress,
[feeAsset]: feeAssetAddress,
[nativeCryptocurrency]: ethers.constants.AddressZero,
[nativeCryptocurrency]: ethers.ZeroAddress,
},
aggregator,
walletAddress,
@@ -120,7 +120,7 @@ export default async function swapLimit({
balances,
{
name: nativeCryptocurrency,
address: ethers.constants.AddressZero,
address: ethers.ZeroAddress,
},
provider,
signer,
@@ -271,7 +271,7 @@ export default async function swapLimit({
BigNumber.ROUND_FLOOR,
);
const unsignedSwapThroughOrionPoolTx = await exchangeContract.populateTransaction.swapThroughOrionPool(
const unsignedSwapThroughOrionPoolTx = await exchangeContract.swapThroughOrionPool.populateTransaction(
amountSpendBlockchainParam,
amountReceiveBlockchainParam,
factoryAddress !== undefined
@@ -280,8 +280,8 @@ export default async function swapLimit({
type === 'exactSpend',
);
unsignedSwapThroughOrionPoolTx.chainId = parseInt(chainId, 10);
unsignedSwapThroughOrionPoolTx.gasPrice = ethers.BigNumber.from(gasPriceWei);
unsignedSwapThroughOrionPoolTx.chainId = BigInt(parseInt(chainId, 10));
unsignedSwapThroughOrionPoolTx.gasPrice = BigInt(gasPriceWei);
unsignedSwapThroughOrionPoolTx.from = walletAddress;
const amountSpendBN = new BigNumber(amountSpend);
@@ -297,19 +297,19 @@ export default async function swapLimit({
NATIVE_CURRENCY_PRECISION,
BigNumber.ROUND_CEIL,
);
unsignedSwapThroughOrionPoolTx.gasLimit = ethers.BigNumber.from(SWAP_THROUGH_ORION_POOL_GAS_LIMIT);
unsignedSwapThroughOrionPoolTx.gasLimit = BigInt(SWAP_THROUGH_ORION_POOL_GAS_LIMIT);
const transactionCost = ethers.BigNumber.from(SWAP_THROUGH_ORION_POOL_GAS_LIMIT).mul(gasPriceWei);
const denormalizedTransactionCost = denormalizeNumber(transactionCost, NATIVE_CURRENCY_PRECISION);
const transactionCost = BigInt(SWAP_THROUGH_ORION_POOL_GAS_LIMIT) * BigInt(gasPriceWei);
const denormalizedTransactionCost = denormalizeNumber(transactionCost, BigInt(NATIVE_CURRENCY_PRECISION));
balanceGuard.registerRequirement({
reason: 'Network fee',
asset: {
name: nativeCryptocurrency,
address: ethers.constants.AddressZero,
address: ethers.ZeroAddress,
},
amount: denormalizedTransactionCost.toString(),
sources: getAvailableSources('network_fee', ethers.constants.AddressZero, 'pool'),
sources: getAvailableSources('network_fee', ethers.ZeroAddress, 'pool'),
});
// if (value.gt(0)) {
@@ -317,10 +317,10 @@ export default async function swapLimit({
// reason: 'Transaction value (extra amount)',
// asset: {
// name: nativeCryptocurrency,
// address: ethers.constants.AddressZero,
// address: ethers.ZeroAddress,
// },
// amount: value.toString(),
// sources: getAvailableSources('amount', ethers.constants.AddressZero, 'pool'),
// sources: getAvailableSources('amount', ethers.ZeroAddress, 'pool'),
// });
// }
@@ -380,7 +380,7 @@ export default async function swapLimit({
gasPriceGwei,
feePercent,
baseAssetAddress,
ethers.constants.AddressZero,
ethers.ZeroAddress,
feeAssetAddress,
allPrices.prices,
);

View File

@@ -1,6 +1,6 @@
import { BigNumber } from 'bignumber.js';
import { ethers } from 'ethers';
import { Exchange__factory } from '@orionprotocol/contracts/lib/ethers-v5/index.js';
import { Exchange__factory } from '@orionprotocol/contracts/lib/ethers-v6/index.js';
import getBalances from '../../utils/getBalances.js';
import BalanceGuard from '../../BalanceGuard.js';
import getAvailableSources from '../../utils/getAvailableFundsSources.js';
@@ -28,7 +28,7 @@ type PoolSwap = {
amountOut: number
through: 'pool'
txHash: string
wait: (confirmations?: number | undefined) => Promise<ethers.providers.TransactionReceipt>
wait: (confirmations?: number | undefined) => Promise<ethers.TransactionReceipt | null>
}
export type Swap = AggregatorOrder | PoolSwap;
@@ -80,7 +80,7 @@ export default async function swapMarket({
const { factories } = await simpleFetch(blockchainService.getPoolsConfig)();
const poolExchangesList = factories !== undefined ? Object.keys(factories) : [];
const gasPriceGwei = ethers.utils.formatUnits(gasPriceWei, 'gwei').toString();
const gasPriceGwei = ethers.formatUnits(gasPriceWei, 'gwei').toString();
const assetInAddress = assetToAddress[assetIn];
if (assetInAddress === undefined) throw new Error(`Asset '${assetIn}' not found`);
@@ -93,7 +93,7 @@ export default async function swapMarket({
{
[assetIn]: assetInAddress,
[feeAsset]: feeAssetAddress,
[nativeCryptocurrency]: ethers.constants.AddressZero,
[nativeCryptocurrency]: ethers.ZeroAddress,
},
aggregator,
walletAddress,
@@ -105,7 +105,7 @@ export default async function swapMarket({
balances,
{
name: nativeCryptocurrency,
address: ethers.constants.AddressZero,
address: ethers.ZeroAddress,
},
provider,
signer,
@@ -221,17 +221,17 @@ export default async function swapMarket({
INTERNAL_PROTOCOL_PRECISION,
BigNumber.ROUND_FLOOR,
);
const unsignedSwapThroughOrionPoolTx = await exchangeContract.populateTransaction.swapThroughOrionPool(
amountSpendBlockchainParam,
amountReceiveBlockchainParam,
const unsignedSwapThroughOrionPoolTx = await exchangeContract.swapThroughOrionPool.populateTransaction(
amountSpendBlockchainParam.toString(),
amountReceiveBlockchainParam.toString(),
factoryAddress !== undefined
? [factoryAddress, ...pathAddresses]
: pathAddresses,
type === 'exactSpend',
);
unsignedSwapThroughOrionPoolTx.chainId = parseInt(chainId, 10);
unsignedSwapThroughOrionPoolTx.gasPrice = ethers.BigNumber.from(gasPriceWei);
unsignedSwapThroughOrionPoolTx.chainId = BigInt(chainId);
unsignedSwapThroughOrionPoolTx.gasPrice = BigInt(gasPriceWei);
unsignedSwapThroughOrionPoolTx.from = walletAddress;
const amountSpendBN = new BigNumber(amountSpend);
@@ -247,19 +247,19 @@ export default async function swapMarket({
NATIVE_CURRENCY_PRECISION,
BigNumber.ROUND_CEIL,
);
unsignedSwapThroughOrionPoolTx.gasLimit = ethers.BigNumber.from(SWAP_THROUGH_ORION_POOL_GAS_LIMIT);
unsignedSwapThroughOrionPoolTx.gasLimit = BigInt(SWAP_THROUGH_ORION_POOL_GAS_LIMIT);
const transactionCost = ethers.BigNumber.from(SWAP_THROUGH_ORION_POOL_GAS_LIMIT).mul(gasPriceWei);
const denormalizedTransactionCost = denormalizeNumber(transactionCost, NATIVE_CURRENCY_PRECISION);
const transactionCost = BigInt(SWAP_THROUGH_ORION_POOL_GAS_LIMIT) * BigInt(gasPriceWei);
const denormalizedTransactionCost = denormalizeNumber(transactionCost, BigInt(NATIVE_CURRENCY_PRECISION));
balanceGuard.registerRequirement({
reason: 'Network fee',
asset: {
name: nativeCryptocurrency,
address: ethers.constants.AddressZero,
address: ethers.ZeroAddress,
},
amount: denormalizedTransactionCost.toString(),
sources: getAvailableSources('network_fee', ethers.constants.AddressZero, 'pool'),
sources: getAvailableSources('network_fee', ethers.ZeroAddress, 'pool'),
});
// if (value.gt(0)) {
@@ -267,10 +267,10 @@ export default async function swapMarket({
// reason: 'Transaction value (extra amount)',
// asset: {
// name: nativeCryptocurrency,
// address: ethers.constants.AddressZero,
// address: ethers.ZeroAddress,
// },
// amount: value.toString(),
// sources: getAvailableSources('amount', ethers.constants.AddressZero, 'pool'),
// sources: getAvailableSources('amount', ethers.ZeroAddress, 'pool'),
// });
// }
@@ -338,7 +338,7 @@ export default async function swapMarket({
gasPriceGwei,
feePercent,
baseAssetAddress,
ethers.constants.AddressZero,
ethers.ZeroAddress,
feeAssetAddress,
allPrices.prices,
);

View File

@@ -1,6 +1,6 @@
import { BigNumber } from 'bignumber.js';
import { ethers } from 'ethers';
import { Exchange__factory } from '@orionprotocol/contracts/lib/ethers-v5/index.js';
import { Exchange__factory } from '@orionprotocol/contracts/lib/ethers-v6/index.js';
import getBalances from '../../utils/getBalances.js';
import BalanceGuard from '../../BalanceGuard.js';
import type Unit from '../index.js';
@@ -50,7 +50,7 @@ export default async function withdraw({
const balances = await getBalances(
{
[asset]: assetAddress,
[nativeCryptocurrency]: ethers.constants.AddressZero,
[nativeCryptocurrency]: ethers.ZeroAddress,
},
aggregator,
walletAddress,
@@ -62,7 +62,7 @@ export default async function withdraw({
balances,
{
name: nativeCryptocurrency,
address: ethers.constants.AddressZero,
address: ethers.ZeroAddress,
},
provider,
signer,
@@ -78,27 +78,27 @@ export default async function withdraw({
sources: ['exchange'],
});
const unsignedTx = await exchangeContract.populateTransaction.withdraw(
const unsignedTx = await exchangeContract.withdraw.populateTransaction(
assetAddress,
normalizeNumber(amount, INTERNAL_PROTOCOL_PRECISION, BigNumber.ROUND_FLOOR),
normalizeNumber(amount, INTERNAL_PROTOCOL_PRECISION, BigNumber.ROUND_FLOOR).toString(),
);
unsignedTx.gasLimit = ethers.BigNumber.from(WITHDRAW_GAS_LIMIT);
unsignedTx.gasLimit = BigInt(WITHDRAW_GAS_LIMIT);
const transactionCost = ethers.BigNumber.from(unsignedTx.gasLimit).mul(gasPriceWei);
const denormalizedTransactionCost = denormalizeNumber(transactionCost, NATIVE_CURRENCY_PRECISION);
const transactionCost = BigInt(unsignedTx.gasLimit) * BigInt(gasPriceWei);
const denormalizedTransactionCost = denormalizeNumber(transactionCost, BigInt(NATIVE_CURRENCY_PRECISION));
balanceGuard.registerRequirement({
reason: 'Network fee',
asset: {
name: nativeCryptocurrency,
address: ethers.constants.AddressZero,
address: ethers.ZeroAddress,
},
amount: denormalizedTransactionCost.toString(),
sources: ['wallet'],
});
unsignedTx.chainId = parseInt(chainId, 10);
unsignedTx.gasPrice = ethers.BigNumber.from(gasPriceWei);
unsignedTx.chainId = BigInt(chainId);
unsignedTx.gasPrice = BigInt(gasPriceWei);
unsignedTx.from = walletAddress;
await balanceGuard.check(true);
@@ -107,11 +107,11 @@ export default async function withdraw({
unsignedTx.nonce = nonce;
const signedTx = await signer.signTransaction(unsignedTx);
const txResponse = await provider.sendTransaction(signedTx);
const txResponse = await provider.broadcastTransaction(signedTx);
console.log(`Withdraw tx sent: ${txResponse.hash}. Waiting for confirmation...`);
try {
const txReceipt = await txResponse.wait();
if (txReceipt.status !== undefined) {
if (txReceipt?.status !== undefined) {
console.log('Withdraw tx confirmed');
} else {
console.log('Withdraw tx failed');

View File

@@ -1,4 +1,4 @@
import { Exchange__factory, IUniswapV2Pair__factory, IUniswapV2Router__factory } from '@orionprotocol/contracts/lib/ethers-v5/index.js';
import { Exchange__factory, IUniswapV2Pair__factory, IUniswapV2Router__factory } from '@orionprotocol/contracts/lib/ethers-v6/index.js';
import { BigNumber } from 'bignumber.js';
import { ethers } from 'ethers';
import { simpleFetch } from 'simple-typed-fetch';
@@ -71,7 +71,7 @@ export default class FarmingManager {
{
[assetA]: assetAAddress,
[assetB]: assetBAddress,
[nativeCryptocurrency]: ethers.constants.AddressZero,
[nativeCryptocurrency]: ethers.ZeroAddress,
},
this.unit.aggregator,
walletAddress,
@@ -81,7 +81,7 @@ export default class FarmingManager {
const balanceGuard = new BalanceGuard(
balances,
{
address: ethers.constants.AddressZero,
address: ethers.ZeroAddress,
name: nativeCryptocurrency,
},
this.unit.provider,
@@ -109,13 +109,13 @@ export default class FarmingManager {
const assetAReserve = pairTokensIsInversed ? _reserve1 : _reserve0;
const assetBReserve = pairTokensIsInversed ? _reserve0 : _reserve1;
const denormalizedAssetAReserve = denormalizeNumber(assetAReserve, assetADecimals);
const denormalizedAssetBReserve = denormalizeNumber(assetBReserve, assetBDecimals);
const denormalizedAssetAReserve = denormalizeNumber(assetAReserve, BigInt(assetADecimals));
const denormalizedAssetBReserve = denormalizeNumber(assetBReserve, BigInt(assetBDecimals));
const price = denormalizedAssetBReserve.div(denormalizedAssetAReserve);
const assetAIsNativeCurrency = assetAAddress === ethers.constants.AddressZero;
const assetBIsNativeCurrency = assetBAddress === ethers.constants.AddressZero;
const assetAIsNativeCurrency = assetAAddress === ethers.ZeroAddress;
const assetBIsNativeCurrency = assetBAddress === ethers.ZeroAddress;
const assetAAmount = assetA === amountAsset ? amountBN : amountBN.div(price);
const assetBAmount = assetA === amountAsset ? amountBN.multipliedBy(price) : amountBN;
@@ -145,33 +145,33 @@ export default class FarmingManager {
sources: ['exchange', 'wallet'],
});
const unsignedTx = await exchangeContract.populateTransaction.withdrawToPool(
const unsignedTx = await exchangeContract.withdrawToPool.populateTransaction(
assetBIsNativeCurrency ? assetBAddress : assetAAddress,
assetBIsNativeCurrency ? assetAAddress : assetBAddress,
assetBIsNativeCurrency
? normalizeNumber(assetBAmount, INTERNAL_PROTOCOL_PRECISION, BigNumber.ROUND_FLOOR)
: normalizeNumber(assetAAmount, INTERNAL_PROTOCOL_PRECISION, BigNumber.ROUND_FLOOR),
? normalizeNumber(assetBAmount, INTERNAL_PROTOCOL_PRECISION, BigNumber.ROUND_FLOOR).toString()
: normalizeNumber(assetAAmount, INTERNAL_PROTOCOL_PRECISION, BigNumber.ROUND_FLOOR).toString(),
assetBIsNativeCurrency
? normalizeNumber(assetAAmount, INTERNAL_PROTOCOL_PRECISION, BigNumber.ROUND_FLOOR)
: normalizeNumber(assetBAmount, INTERNAL_PROTOCOL_PRECISION, BigNumber.ROUND_FLOOR),
? normalizeNumber(assetAAmount, INTERNAL_PROTOCOL_PRECISION, BigNumber.ROUND_FLOOR).toString()
: normalizeNumber(assetBAmount, INTERNAL_PROTOCOL_PRECISION, BigNumber.ROUND_FLOOR).toString(),
assetBIsNativeCurrency
? normalizeNumber(assetBAmountWithSlippage, INTERNAL_PROTOCOL_PRECISION, BigNumber.ROUND_FLOOR)
: normalizeNumber(assetAAmountWithSlippage, INTERNAL_PROTOCOL_PRECISION, BigNumber.ROUND_FLOOR),
? normalizeNumber(assetBAmountWithSlippage, INTERNAL_PROTOCOL_PRECISION, BigNumber.ROUND_FLOOR).toString()
: normalizeNumber(assetAAmountWithSlippage, INTERNAL_PROTOCOL_PRECISION, BigNumber.ROUND_FLOOR).toString(),
assetBIsNativeCurrency
? normalizeNumber(assetAAmountWithSlippage, INTERNAL_PROTOCOL_PRECISION, BigNumber.ROUND_FLOOR)
: normalizeNumber(assetBAmountWithSlippage, INTERNAL_PROTOCOL_PRECISION, BigNumber.ROUND_FLOOR),
? normalizeNumber(assetAAmountWithSlippage, INTERNAL_PROTOCOL_PRECISION, BigNumber.ROUND_FLOOR).toString()
: normalizeNumber(assetBAmountWithSlippage, INTERNAL_PROTOCOL_PRECISION, BigNumber.ROUND_FLOOR).toString(),
);
const gasPrice = await this.unit.provider.getGasPrice();
const { gasPrice, maxFeePerGas } = await this.unit.provider.getFeeData();
const transactionCost = ethers.BigNumber.from(ADD_LIQUIDITY_GAS_LIMIT).mul(gasPrice);
const denormalizedTransactionCost = denormalizeNumber(transactionCost, NATIVE_CURRENCY_PRECISION);
const transactionCost = BigInt(ADD_LIQUIDITY_GAS_LIMIT) * (gasPrice ?? 0n);
const denormalizedTransactionCost = denormalizeNumber(transactionCost, BigInt(NATIVE_CURRENCY_PRECISION));
balanceGuard.registerRequirement({
reason: 'Network fee',
asset: {
name: nativeCryptocurrency,
address: ethers.constants.AddressZero,
address: ethers.ZeroAddress,
},
amount: denormalizedTransactionCost.toString(),
sources: ['wallet'],
@@ -195,8 +195,11 @@ export default class FarmingManager {
}
}
if (gasPrice !== null && maxFeePerGas !== null) {
unsignedTx.gasPrice = gasPrice;
unsignedTx.maxFeePerGas = maxFeePerGas;
}
unsignedTx.chainId = network.chainId;
unsignedTx.gasPrice = gasPrice;
unsignedTx.nonce = nonce;
unsignedTx.from = walletAddress;
const gasLimit = await this.unit.provider.estimateGas(unsignedTx);
@@ -205,13 +208,13 @@ export default class FarmingManager {
await balanceGuard.check(true);
const signedTx = await signer.signTransaction(unsignedTx);
const txResponse = await this.unit.provider.sendTransaction(signedTx);
const txResponse = await this.unit.provider.broadcastTransaction(signedTx);
console.log(`Add liquidity tx sent: ${txResponse.hash}. Waiting for confirmation...`);
const txReceipt = await txResponse.wait();
if (txReceipt.status === 1) {
console.log(`Add liquidity tx confirmed: ${txReceipt.transactionHash}`);
if (txReceipt?.status === 1) {
console.log(`Add liquidity tx confirmed: ${txReceipt.hash}`);
} else {
console.log(`Add liquidity tx failed: ${txReceipt.transactionHash}`);
console.log(`Add liquidity tx failed: ${txReceipt?.hash}`);
}
}
@@ -254,7 +257,7 @@ export default class FarmingManager {
[assetA]: assetAAddress,
[assetB]: assetBAddress,
[`${poolName} LP Token`]: pool.lpTokenAddress,
[nativeCryptocurrency]: ethers.constants.AddressZero,
[nativeCryptocurrency]: ethers.ZeroAddress,
},
this.unit.aggregator,
walletAddress,
@@ -265,7 +268,7 @@ export default class FarmingManager {
const balanceGuard = new BalanceGuard(
balances,
{
address: ethers.constants.AddressZero,
address: ethers.ZeroAddress,
name: nativeCryptocurrency,
},
this.unit.provider,
@@ -298,8 +301,8 @@ export default class FarmingManager {
const assetAReserve = pairTokensIsInversed ? _reserve1 : _reserve0;
const assetBReserve = pairTokensIsInversed ? _reserve0 : _reserve1;
const denormalizedAssetAReserve = denormalizeNumber(assetAReserve, assetADecimals);
const denormalizedAssetBReserve = denormalizeNumber(assetBReserve, assetBDecimals);
const denormalizedAssetAReserve = denormalizeNumber(assetAReserve, BigInt(assetADecimals));
const denormalizedAssetBReserve = denormalizeNumber(assetBReserve, BigInt(assetBDecimals));
const denormalizedUserPooledAssetA = denormalizedAssetAReserve.multipliedBy(userShare);
const denormalizedUserPooledAssetB = denormalizedAssetBReserve.multipliedBy(userShare);
@@ -307,8 +310,8 @@ export default class FarmingManager {
const denormalizedUserPooledAssetAWithSlippage = denormalizedUserPooledAssetA.multipliedBy(1 - ADD_LIQUIDITY_SLIPPAGE);
const denormalizedUserPooledAssetBWithSlippage = denormalizedUserPooledAssetB.multipliedBy(1 - ADD_LIQUIDITY_SLIPPAGE);
const assetAIsNativeCurrency = assetAAddress === ethers.constants.AddressZero;
const assetBIsNativeCurrency = assetBAddress === ethers.constants.AddressZero;
const assetAIsNativeCurrency = assetAAddress === ethers.ZeroAddress;
const assetBIsNativeCurrency = assetBAddress === ethers.ZeroAddress;
balanceGuard.registerRequirement({
reason: `${poolName} liquidity`,
@@ -321,9 +324,9 @@ export default class FarmingManager {
sources: ['wallet'],
});
let unsignedTx: ethers.PopulatedTransaction;
let unsignedTx: ethers.TransactionLike;
if (assetAIsNativeCurrency || assetBIsNativeCurrency) {
unsignedTx = await routerContract.populateTransaction.removeLiquidityETH(
unsignedTx = await routerContract.removeLiquidityETH.populateTransaction(
assetBIsNativeCurrency ? assetAAddress : assetBAddress, // token
lpTokenUserBalance,
assetBIsNativeCurrency
@@ -331,28 +334,28 @@ export default class FarmingManager {
denormalizedUserPooledAssetAWithSlippage,
assetADecimals,
BigNumber.ROUND_FLOOR,
)
).toString()
: normalizeNumber(
denormalizedUserPooledAssetBWithSlippage,
assetBDecimals,
BigNumber.ROUND_FLOOR,
), // token min
).toString(), // token min
assetBIsNativeCurrency
? normalizeNumber(
denormalizedUserPooledAssetBWithSlippage,
assetBDecimals,
BigNumber.ROUND_FLOOR,
)
).toString()
: normalizeNumber(
denormalizedUserPooledAssetAWithSlippage,
assetADecimals,
BigNumber.ROUND_FLOOR,
), // eth min
).toString(), // eth min
walletAddress,
Math.floor(Date.now() / 1000) + 60 * 20,
);
} else {
unsignedTx = await routerContract.populateTransaction.removeLiquidity(
unsignedTx = await routerContract.removeLiquidity.populateTransaction(
assetAAddress,
assetBAddress,
lpTokenUserBalance,
@@ -360,27 +363,27 @@ export default class FarmingManager {
denormalizedUserPooledAssetAWithSlippage,
assetADecimals,
BigNumber.ROUND_FLOOR,
),
).toString(),
normalizeNumber(
denormalizedUserPooledAssetBWithSlippage,
assetBDecimals,
BigNumber.ROUND_FLOOR,
),
).toString(),
walletAddress,
Math.floor(Date.now() / 1000) + 60 * 20,
);
}
const gasPrice = await this.unit.provider.getGasPrice();
const { gasPrice } = await this.unit.provider.getFeeData()
const transactionCost = ethers.BigNumber.from(ADD_LIQUIDITY_GAS_LIMIT).mul(gasPrice);
const denormalizedTransactionCost = denormalizeNumber(transactionCost, NATIVE_CURRENCY_PRECISION);
const transactionCost = BigInt(ADD_LIQUIDITY_GAS_LIMIT) * (gasPrice ?? 0n);
const denormalizedTransactionCost = denormalizeNumber(transactionCost, BigInt(NATIVE_CURRENCY_PRECISION));
balanceGuard.registerRequirement({
reason: 'Network fee',
asset: {
name: nativeCryptocurrency,
address: ethers.constants.AddressZero,
address: ethers.ZeroAddress,
},
amount: denormalizedTransactionCost.toString(),
sources: ['wallet'],
@@ -398,13 +401,13 @@ export default class FarmingManager {
unsignedTx.gasLimit = gasLimit;
const signedTx = await signer.signTransaction(unsignedTx);
const txResponse = await this.unit.provider.sendTransaction(signedTx);
const txResponse = await this.unit.provider.broadcastTransaction(signedTx);
console.log(`Remove all liquidity tx sent: ${txResponse.hash}. Waiting for confirmation...`);
const txReceipt = await txResponse.wait();
if (txReceipt.status === 1) {
console.log(`Remove all liquidity tx confirmed: ${txReceipt.transactionHash}`);
if (txReceipt?.status === 1) {
console.log(`Remove all liquidity tx confirmed: ${txReceipt.hash}`);
} else {
console.log(`Remove all liquidity tx failed: ${txReceipt.transactionHash}`);
console.log(`Remove all liquidity tx failed: ${txReceipt?.hash}`);
}
}
}

View File

@@ -1,27 +1,34 @@
import { ethers } from 'ethers';
import { JsonRpcProvider } from 'ethers';
import { Aggregator } from '../services/Aggregator/index.js';
import { BlockchainService } from '../services/BlockchainService/index.js';
import { PriceFeed } from '../services/PriceFeed/index.js';
import type { KnownEnv, SupportedChainId, VerboseUnitConfig } from '../types.js';
import type {
KnownEnv,
SupportedChainId,
VerboseUnitConfig,
} from '../types.js';
import Exchange from './Exchange/index.js';
import FarmingManager from './FarmingManager/index.js';
import { chains, envs } from '../config/index.js';
import type { networkCodes } from '../constants/index.js';
import { IntegratorService } from '../services/Integrator/index.js';
type KnownConfig = {
env: KnownEnv
chainId: SupportedChainId
}
};
export default class Unit {
public readonly networkCode: typeof networkCodes[number];
public readonly networkCode: (typeof networkCodes)[number];
public readonly chainId: SupportedChainId;
public readonly provider: ethers.providers.StaticJsonRpcProvider;
public readonly provider: JsonRpcProvider;
public readonly blockchainService: BlockchainService;
public readonly integrator: IntegratorService;
public readonly aggregator: Aggregator;
public readonly priceFeed: PriceFeed;
@@ -37,13 +44,33 @@ export default class Unit {
constructor(config: KnownConfig | VerboseUnitConfig) {
if ('env' in config) {
const staticConfig = envs[config.env];
if (!staticConfig) throw new Error(`Invalid environment: ${config.env}. Available environments: ${Object.keys(envs).join(', ')}`);
if (!staticConfig) {
throw new Error(
`Invalid environment: ${
config.env
}. Available environments: ${Object.keys(envs).join(', ')}`
);
}
const chainConfig = chains[config.chainId];
if (!chainConfig) throw new Error(`Invalid chainId: ${config.chainId}. Available chainIds: ${Object.keys(chains).join(', ')}`);
if (!chainConfig) {
throw new Error(
`Invalid chainId: ${
config.chainId
}. Available chainIds: ${Object.keys(chains).join(', ')}`
);
}
const networkConfig = staticConfig.networks[config.chainId];
if (!networkConfig) throw new Error(`Invalid chainId: ${config.chainId}. Available chainIds: ${Object.keys(staticConfig.networks).join(', ')}`);
if (!networkConfig) {
throw new Error(
`Invalid chainId: ${
config.chainId
}. Available chainIds: ${Object.keys(staticConfig.networks).join(
', '
)}`
);
}
this.config = {
chainId: config.chainId,
nodeJsonRpc: networkConfig.rpc ?? chainConfig.rpc,
@@ -58,29 +85,43 @@ export default class Unit {
priceFeed: {
api: networkConfig.api + networkConfig.services.priceFeed.all,
},
integrator: {
api: networkConfig.api + networkConfig.services.integrator.http,
},
},
}
};
} else {
this.config = config;
}
const chainInfo = chains[config.chainId];
if (!chainInfo) throw new Error('Chain info is required');
this.chainId = config.chainId;
this.networkCode = chainInfo.code;
this.contracts = chainInfo.contracts
this.contracts = chainInfo.contracts;
const intNetwork = parseInt(this.chainId, 10);
if (Number.isNaN(intNetwork)) throw new Error('Invalid chainId (not a number)' + this.chainId);
this.provider = new ethers.providers.StaticJsonRpcProvider(this.config.nodeJsonRpc, intNetwork);
if (Number.isNaN(intNetwork)) {
throw new Error('Invalid chainId (not a number)' + this.chainId);
}
this.provider = new JsonRpcProvider(this.config.nodeJsonRpc, intNetwork);
this.provider.pollingInterval = 1000;
this.blockchainService = new BlockchainService(this.config.services.blockchainService.http, this.config.basicAuth);
this.blockchainService = new BlockchainService(
this.config.services.blockchainService.http,
this.config.basicAuth
);
this.integrator = new IntegratorService(
this.config.services.integrator.api,
intNetwork
);
this.aggregator = new Aggregator(
this.config.services.aggregator.http,
this.config.services.aggregator.ws,
this.config.basicAuth,
this.config.basicAuth
);
this.priceFeed = new PriceFeed(
this.config.services.priceFeed.api,
this.config.basicAuth
);
this.priceFeed = new PriceFeed(this.config.services.priceFeed.api, this.config.basicAuth);
this.exchange = new Exchange(this);
this.farmingManager = new FarmingManager(this);
}