feat: update ethers@6

fix: bigint errors

fix: TS errors

fix: gasLimit fetch

fix: review comments

fix: contracts errors

chore: bump rc version

fix: revert wrong fix

fix: ts config

fix: ts config

fix: ts config

feat: update signer
This commit is contained in:
Oleg Nechiporenko
2023-09-07 00:12:07 +03:00
parent 27c426e815
commit c2a4084158
38 changed files with 409 additions and 608 deletions

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';
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,11 +1,10 @@
import type { ExchangeWithGenericSwap } from '@orionprotocol/contracts/lib/ethers-v5/Exchange.js';
import { UniswapV3Pool__factory, ERC20__factory, SwapExecutor__factory, CurveRegistry__factory } from '@orionprotocol/contracts/lib/ethers-v5/index.js';
import { BigNumber, ethers, type BigNumberish } from 'ethers';
import { concat, defaultAbiCoder, type BytesLike } from 'ethers/lib/utils.js';
import type { ExchangeWithGenericSwap } from '@orionprotocol/contracts/lib/ethers-v6/Exchange.js';
import { UniswapV3Pool__factory, ERC20__factory, SwapExecutor__factory, CurveRegistry__factory } from '@orionprotocol/contracts/lib/ethers-v6';
import { ethers, type BigNumberish, type AddressLike, concat, type BytesLike } from 'ethers';
import { safeGet, SafeArray } from '../../utils/safeGetters.js';
import type Unit from '../index.js';
import { simpleFetch } from 'simple-typed-fetch';
import type { PromiseOrValue } from '@orionprotocol/contracts/lib/ethers-v5/common.js';
import { BigNumber } from 'bignumber.js';
const EXECUTOR_SWAP_FUNCTION = 'func_70LYiww'
@@ -64,20 +63,24 @@ export default async function generateSwapCalldata({
flags: 0
}
const exchangeToNativeDecimals = async (token: PromiseOrValue<string>) => {
token = await token
let decimals = 18
if (token !== ethers.constants.AddressZero) {
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.from(amount).mul(BigNumber.from(10).pow(decimals)).div(BigNumber.from(10).pow(8))
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.constants.AddressZero) swapInfo.assetIn = wethAddress
if (swapInfo.assetOut == ethers.constants.AddressZero) swapInfo.assetOut = wethAddress
if (swapInfo.assetIn == ethers.ZeroAddress) swapInfo.assetIn = wethAddress
if (swapInfo.assetOut == ethers.ZeroAddress) swapInfo.assetOut = wethAddress
return swapInfo;
});
@@ -94,16 +97,16 @@ export default async function generateSwapCalldata({
break;
}
case 'UniswapV3': {
calldata = await generateUni3Calls(amountNativeDecimals, exchangeContractAddress, path, unit.provider)
calldata = await generateUni3Calls(amountNativeDecimals.toString(), exchangeContractAddress, path, unit.provider)
break;
}
case 'OrionV3': {
calldata = await generateOrion3Calls(amountNativeDecimals, exchangeContractAddress, path, unit.provider)
calldata = await generateOrion3Calls(amountNativeDecimals.toString(), exchangeContractAddress, path, unit.provider)
break;
}
case 'Curve': {
calldata = await generateCurveStableSwapCalls(
amountNativeDecimals,
amountNativeDecimals.toString(),
exchangeContractAddress,
swapExecutorContractAddress ?? '',
path,
@@ -134,7 +137,7 @@ export async function generateUni2Calls(
currentSwap.pool,
currentSwap.assetIn,
currentSwap.assetOut,
defaultAbiCoder.encode(['uint256'], [concat(['0x03', nextSwap.pool])]),
ethers.AbiCoder.defaultAbiCoder().encode(['uint256'], [concat(['0x03', nextSwap.pool])]),
]
)
calls.push(addCallParams(calldata))
@@ -145,7 +148,7 @@ export async function generateUni2Calls(
lastSwap.pool,
lastSwap.assetIn,
lastSwap.assetOut,
defaultAbiCoder.encode(['uint256'], [concat(['0x03', exchangeAddress])]),
ethers.AbiCoder.defaultAbiCoder().encode(['uint256'], [concat(['0x03', exchangeAddress])]),
])
calls.push(addCallParams(calldata))
@@ -156,22 +159,22 @@ async function generateUni3Calls(
amount: BigNumberish,
exchangeContractAddress: string,
path: SafeArray<SwapInfo>,
provider: ethers.providers.JsonRpcProvider
provider: ethers.JsonRpcApiProvider
) {
const encodedPools: BytesLike[] = []
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.constants.AddressZero
const unwrapWETH = swap.assetOut === 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]))
encodedPools.push(encodedPool)
}
const executorInterface = SwapExecutor__factory.createInterface()
@@ -185,22 +188,22 @@ async function generateOrion3Calls(
amount: BigNumberish,
exchangeContractAddress: string,
path: SafeArray<SwapInfo>,
provider: ethers.providers.JsonRpcProvider
provider: ethers.JsonRpcApiProvider
) {
const encodedPools: BytesLike[] = []
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.constants.AddressZero
const unwrapWETH = swap.assetOut === 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]))
encodedPools.push(encodedPool)
}
const executorInterface = SwapExecutor__factory.createInterface()
@@ -215,7 +218,7 @@ async function generateCurveStableSwapCalls(
exchangeContractAddress: string,
executorAddress: string,
path: SafeArray<SwapInfo>,
provider: ethers.providers.JsonRpcProvider,
provider: ethers.JsonRpcProvider,
curveRegistry: string
) {
if (path.length > 1) {
@@ -231,12 +234,12 @@ async function generateCurveStableSwapCalls(
const executorAllowance = await firstToken.allowance(executorAddress, swap.pool)
const calls: BytesLike[] = []
if (executorAllowance.lt(amount)) {
if (executorAllowance < BigInt(amount)) {
const calldata = addCallParams(
executorInterface.encodeFunctionData('safeApprove', [
swap.assetIn,
swap.pool,
ethers.constants.MaxUint256
ethers.MaxUint256
])
)
calls.push(calldata)
@@ -265,28 +268,28 @@ 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
}
async function generateCalls(calls: BytesLike[]) {
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)
}

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

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

@@ -7,6 +7,7 @@ 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 type { JsonRpcProvider } from 'ethers';
type KnownConfig = {
env: KnownEnv
@@ -18,7 +19,7 @@ export default class Unit {
public readonly chainId: SupportedChainId;
public readonly provider: ethers.providers.StaticJsonRpcProvider;
public readonly provider: JsonRpcProvider;
public readonly blockchainService: BlockchainService;
@@ -65,13 +66,12 @@ export default class Unit {
}
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
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);
this.provider = new ethers.JsonRpcProvider(this.config.nodeJsonRpc, intNetwork);
this.provider.pollingInterval = 1000;
this.blockchainService = new BlockchainService(this.config.services.blockchainService.http, this.config.basicAuth);