From 42e3e2a3eb39fd7794be0d2df7bbc0d0c8468b30 Mon Sep 17 00:00:00 2001 From: Aleksandr Kraiz Date: Mon, 13 Feb 2023 18:13:30 +0400 Subject: [PATCH] Fix --- .eslintrc.js | 2 ++ src/BalanceGuard.ts | 13 ++++++----- src/OrionUnit/Exchange/deposit.ts | 8 +++---- src/OrionUnit/Exchange/getSwapInfo.ts | 7 +++--- src/OrionUnit/Exchange/swapMarket.ts | 32 ++++++++++++++++----------- src/OrionUnit/Exchange/withdraw.ts | 6 ++--- src/__tests__/basic.test.ts | 5 ++++- src/crypt/signCFDOrder.ts | 3 +-- src/crypt/signCancelOrder.ts | 3 +-- src/crypt/signOrder.ts | 3 +-- src/utils/checkIsToken.ts | 1 - src/utils/getBalance.ts | 8 +++---- src/utils/getNativeCryptocurrency.ts | 12 +++++----- src/utils/index.ts | 1 + src/utils/objectKeys.ts | 2 +- 15 files changed, 56 insertions(+), 50 deletions(-) diff --git a/.eslintrc.js b/.eslintrc.js index a546fb3..e718c7f 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -96,6 +96,8 @@ module.exports = { 2, { ignoreComments: true, + ignoreUrls: true, + ignoreTemplateLiterals: true, } ], 'import/extensions': [ diff --git a/src/BalanceGuard.ts b/src/BalanceGuard.ts index 44f49d0..a09819f 100644 --- a/src/BalanceGuard.ts +++ b/src/BalanceGuard.ts @@ -2,7 +2,6 @@ import BigNumber from 'bignumber.js'; import { ethers } from 'ethers'; import clone from 'just-clone'; import { ERC20__factory } from '@orionprotocol/contracts'; -import { utils } from '.'; import { APPROVE_ERC20_GAS_LIMIT, NATIVE_CURRENCY_PRECISION } from './constants'; import type { AggregatedBalanceRequirement, ApproveFix, Asset, BalanceIssue, BalanceRequirement, Source, @@ -276,8 +275,10 @@ export default class BalanceGuard { const approveTransactionCost = ethers.BigNumber .from(APPROVE_ERC20_GAS_LIMIT) .mul(gasPriceWei); - const denormalizedApproveTransactionCost = utils - .denormalizeNumber(approveTransactionCost, NATIVE_CURRENCY_PRECISION); + const denormalizedApproveTransactionCost = denormalizeNumber( + approveTransactionCost, + NATIVE_CURRENCY_PRECISION + ); requiredApproves.items = { ...requiredApproves.items, @@ -367,8 +368,10 @@ export default class BalanceGuard { const approveTransactionCost = ethers.BigNumber .from(APPROVE_ERC20_GAS_LIMIT) .mul(gasPriceWei); - const denormalizedApproveTransactionCost = utils - .denormalizeNumber(approveTransactionCost, NATIVE_CURRENCY_PRECISION); + const denormalizedApproveTransactionCost = denormalizeNumber( + approveTransactionCost, + NATIVE_CURRENCY_PRECISION + ); requiredApproves.items = { ...requiredApproves.items, diff --git a/src/OrionUnit/Exchange/deposit.ts b/src/OrionUnit/Exchange/deposit.ts index 81376d4..c4c3734 100644 --- a/src/OrionUnit/Exchange/deposit.ts +++ b/src/OrionUnit/Exchange/deposit.ts @@ -1,15 +1,13 @@ -/* eslint-disable max-len */ import BigNumber from 'bignumber.js'; import { ethers } from 'ethers'; import { Exchange__factory } from '@orionprotocol/contracts'; import getBalances from '../../utils/getBalances'; import BalanceGuard from '../../BalanceGuard'; import type OrionUnit from '..'; -import { utils } from '../..'; import { DEPOSIT_ERC20_GAS_LIMIT, DEPOSIT_ETH_GAS_LIMIT, INTERNAL_ORION_PRECISION, NATIVE_CURRENCY_PRECISION, } from '../../constants'; -import { normalizeNumber } from '../../utils'; +import { denormalizeNumber, normalizeNumber } from '../../utils'; import getNativeCryptocurrency from '../../utils/getNativeCryptocurrency'; import simpleFetch from '../../simpleFetch'; @@ -77,7 +75,7 @@ export default async function deposit({ name: asset, address: assetAddress, }, - amount: amount.toString(), + amount: amountBN.toString(), spenderAddress: exchangeContractAddress, sources: ['wallet'], }); @@ -96,7 +94,7 @@ export default async function deposit({ } const transactionCost = ethers.BigNumber.from(unsignedTx.gasLimit).mul(gasPriceWei); - const denormalizedTransactionCost = utils.denormalizeNumber(transactionCost, NATIVE_CURRENCY_PRECISION); + const denormalizedTransactionCost = denormalizeNumber(transactionCost, NATIVE_CURRENCY_PRECISION); balanceGuard.registerRequirement({ reason: 'Network fee', diff --git a/src/OrionUnit/Exchange/getSwapInfo.ts b/src/OrionUnit/Exchange/getSwapInfo.ts index 20b9b8a..232bc8a 100644 --- a/src/OrionUnit/Exchange/getSwapInfo.ts +++ b/src/OrionUnit/Exchange/getSwapInfo.ts @@ -1,12 +1,11 @@ import BigNumber from 'bignumber.js'; import { ethers } from 'ethers'; -import { utils } from '../..'; import { NATIVE_CURRENCY_PRECISION, SWAP_THROUGH_ORION_POOL_GAS_LIMIT } from '../../constants'; import { type OrionAggregator } from '../../services/OrionAggregator'; import { type OrionBlockchain } from '../../services/OrionBlockchain'; import simpleFetch from '../../simpleFetch'; -import getNativeCryptocurrency from '../../utils/getNativeCryptocurrency'; +import { calculateFeeInFeeAsset, denormalizeNumber, getNativeCryptocurrency } from '../../utils'; export type GetSwapInfoParams = { type: 'exactSpend' | 'exactReceive' @@ -101,7 +100,7 @@ export default async function getSwapInfo({ if (route === 'pool') { const transactionCost = ethers.BigNumber.from(SWAP_THROUGH_ORION_POOL_GAS_LIMIT).mul(gasPriceWei); - const denormalizedTransactionCost = utils.denormalizeNumber(transactionCost, NATIVE_CURRENCY_PRECISION); + const denormalizedTransactionCost = denormalizeNumber(transactionCost, NATIVE_CURRENCY_PRECISION); return { route, @@ -134,7 +133,7 @@ export default async function getSwapInfo({ const { orionFeeInFeeAsset, networkFeeInFeeAsset, - } = utils.calculateFeeInFeeAsset( + } = calculateFeeInFeeAsset( swapInfo.orderInfo.amount, feeAssetPriceInOrn, baseAssetPriceInOrn, diff --git a/src/OrionUnit/Exchange/swapMarket.ts b/src/OrionUnit/Exchange/swapMarket.ts index e82980d..5639e96 100644 --- a/src/OrionUnit/Exchange/swapMarket.ts +++ b/src/OrionUnit/Exchange/swapMarket.ts @@ -1,4 +1,3 @@ -/* eslint-disable max-len */ import BigNumber from 'bignumber.js'; import { ethers } from 'ethers'; import { Exchange__factory } from '@orionprotocol/contracts'; @@ -6,10 +5,11 @@ import getBalances from '../../utils/getBalances'; import BalanceGuard from '../../BalanceGuard'; import getAvailableSources from '../../utils/getAvailableFundsSources'; import type OrionUnit from '..'; -import { crypt, utils } from '../..'; import { INTERNAL_ORION_PRECISION, NATIVE_CURRENCY_PRECISION, SWAP_THROUGH_ORION_POOL_GAS_LIMIT } from '../../constants'; import getNativeCryptocurrency from '../../utils/getNativeCryptocurrency'; import simpleFetch from '../../simpleFetch'; +import { calculateFeeInFeeAsset, denormalizeNumber, normalizeNumber } from '../../utils'; +import { signOrder } from '../../crypt'; export type SwapMarketParams = { type: 'exactSpend' | 'exactReceive' @@ -62,11 +62,11 @@ export default async function swapMarket({ if (slippagePercent === '') throw new Error('Slippage percent can not be empty'); const amountBN = new BigNumber(amount); - if (amountBN.isNaN()) throw new Error(`Amount '${amount.toString()}' is not a number`); - if (amountBN.lte(0)) throw new Error(`Amount '${amount.toString()}' should be greater than 0`); + if (amountBN.isNaN()) throw new Error(`Amount '${amountBN.toString()}' is not a number`); + if (amountBN.lte(0)) throw new Error(`Amount '${amountBN.toString()}' should be greater than 0`); const slippagePercentBN = new BigNumber(slippagePercent); - if (slippagePercentBN.isNaN()) throw new Error(`Slippage percent '${slippagePercent.toString()}' is not a number`); + if (slippagePercentBN.isNaN()) throw new Error(`Slippage percent '${slippagePercentBN.toString()}' is not a number`); if (slippagePercentBN.lte(0)) throw new Error('Slippage percent should be greater than 0'); if (slippagePercentBN.gte(50)) throw new Error('Slippage percent should be less than 50'); @@ -95,7 +95,9 @@ export default async function swapMarket({ const assetInAddress = assetToAddress[assetIn]; if (assetInAddress === undefined) throw new Error(`Asset '${assetIn}' not found`); const feeAssetAddress = assetToAddress[feeAsset]; - if (feeAssetAddress === undefined) throw new Error(`Fee asset '${feeAsset}' not found. Available assets: ${Object.keys(feeAssets).join(', ')}`); + if (feeAssetAddress === undefined) { + throw new Error(`Fee asset '${feeAsset}' not found. Available assets: ${Object.keys(feeAssets).join(', ')}`); + } const balances = await getBalances( { @@ -157,7 +159,11 @@ export default async function swapMarket({ if (qtyDecimalPlaces === null) throw new Error('Qty decimal places is null. Likely amount is -Infinity, +Infinity or NaN'); - if (qtyPrecisionBN.lt(qtyDecimalPlaces)) throw new Error(`Actual amount decimal places (${qtyDecimalPlaces}) is greater than max allowed decimal places (${qtyPrecisionBN.toString()}) on pair ${baseAssetName}-${quoteAssetName}`); + if (qtyPrecisionBN.lt(qtyDecimalPlaces)) { + throw new Error( + `Actual amount decimal places (${qtyDecimalPlaces}) is greater than max allowed decimal places (${qtyPrecisionBN.toString()}) on pair ${baseAssetName}-${quoteAssetName}` + ); + } let route: 'aggregator' | 'pool'; @@ -215,12 +221,12 @@ export default async function swapMarket({ }); const amountReceive = swapInfo.type === 'exactReceive' ? swapInfo.amountOut : amountOutWithSlippage; - const amountSpendBlockchainParam = utils.normalizeNumber( + const amountSpendBlockchainParam = normalizeNumber( amountSpend, INTERNAL_ORION_PRECISION, BigNumber.ROUND_CEIL, ); - const amountReceiveBlockchainParam = utils.normalizeNumber( + const amountReceiveBlockchainParam = normalizeNumber( amountReceive, INTERNAL_ORION_PRECISION, BigNumber.ROUND_FLOOR, @@ -246,7 +252,7 @@ export default async function swapMarket({ if (assetIn === nativeCryptocurrency && amountSpendBN.gt(denormalizedAssetInExchangeBalance)) { value = amountSpendBN.minus(denormalizedAssetInExchangeBalance); } - unsignedSwapThroughOrionPoolTx.value = utils.normalizeNumber( + unsignedSwapThroughOrionPoolTx.value = normalizeNumber( value.dp(INTERNAL_ORION_PRECISION, BigNumber.ROUND_CEIL), NATIVE_CURRENCY_PRECISION, BigNumber.ROUND_CEIL, @@ -254,7 +260,7 @@ export default async function swapMarket({ unsignedSwapThroughOrionPoolTx.gasLimit = ethers.BigNumber.from(SWAP_THROUGH_ORION_POOL_GAS_LIMIT); const transactionCost = ethers.BigNumber.from(SWAP_THROUGH_ORION_POOL_GAS_LIMIT).mul(gasPriceWei); - const denormalizedTransactionCost = utils.denormalizeNumber(transactionCost, NATIVE_CURRENCY_PRECISION); + const denormalizedTransactionCost = denormalizeNumber(transactionCost, NATIVE_CURRENCY_PRECISION); balanceGuard.registerRequirement({ reason: 'Network fee', @@ -341,7 +347,7 @@ export default async function swapMarket({ const feePercent = feeAssets[feeAsset]; if (feePercent === undefined) throw new Error(`Fee asset ${feeAsset} not available`); - const { orionFeeInFeeAsset, networkFeeInFeeAsset, totalFeeInFeeAsset } = utils.calculateFeeInFeeAsset( + const { orionFeeInFeeAsset, networkFeeInFeeAsset, totalFeeInFeeAsset } = calculateFeeInFeeAsset( swapInfo.orderInfo.amount, feeAssetPriceInOrn, baseAssetPriceInOrn, @@ -381,7 +387,7 @@ export default async function swapMarket({ await balanceGuard.check(options?.autoApprove); - const signedOrder = await crypt.signOrder( + const signedOrder = await signOrder( baseAssetAddress, quoteAssetAddress, swapInfo.orderInfo.side, diff --git a/src/OrionUnit/Exchange/withdraw.ts b/src/OrionUnit/Exchange/withdraw.ts index e909075..fd73f7d 100644 --- a/src/OrionUnit/Exchange/withdraw.ts +++ b/src/OrionUnit/Exchange/withdraw.ts @@ -1,15 +1,13 @@ -/* eslint-disable max-len */ import BigNumber from 'bignumber.js'; import { ethers } from 'ethers'; import { Exchange__factory } from '@orionprotocol/contracts'; import getBalances from '../../utils/getBalances'; import BalanceGuard from '../../BalanceGuard'; import type OrionUnit from '..'; -import { utils } from '../..'; import { INTERNAL_ORION_PRECISION, NATIVE_CURRENCY_PRECISION, WITHDRAW_GAS_LIMIT, } from '../../constants'; -import { normalizeNumber } from '../../utils'; +import { denormalizeNumber, normalizeNumber } from '../../utils'; import getNativeCryptocurrency from '../../utils/getNativeCryptocurrency'; import simpleFetch from '../../simpleFetch'; @@ -87,7 +85,7 @@ export default async function withdraw({ unsignedTx.gasLimit = ethers.BigNumber.from(WITHDRAW_GAS_LIMIT); const transactionCost = ethers.BigNumber.from(unsignedTx.gasLimit).mul(gasPriceWei); - const denormalizedTransactionCost = utils.denormalizeNumber(transactionCost, NATIVE_CURRENCY_PRECISION); + const denormalizedTransactionCost = denormalizeNumber(transactionCost, NATIVE_CURRENCY_PRECISION); balanceGuard.registerRequirement({ reason: 'Network fee', diff --git a/src/__tests__/basic.test.ts b/src/__tests__/basic.test.ts index 54abae1..37895b5 100644 --- a/src/__tests__/basic.test.ts +++ b/src/__tests__/basic.test.ts @@ -165,7 +165,7 @@ describe('Orion', () => { } }); - const orionUnit = orion.unitsArray[0]; + const [orionUnit] = orion.unitsArray; if (!orionUnit) { throw new Error('Orion unit is not defined'); } @@ -177,6 +177,9 @@ describe('Orion', () => { expect(orionUnit.chainId).toBe(SupportedChainId.MAINNET); // expect(orionUnit.env).toBeUndefined(); // expect(orion.units[0]?.orionAggregator.api).toBe('http://localhost:3001'); + if (server1.port === undefined) { + throw new Error('Server 1 port is not defined'); + } expect(orionUnit.orionAggregator.ws.api).toBe(`ws://localhost:${server1.port}/v1`); expect(orionUnit.orionBlockchain.api).toBe(orionBlockchainAPI); expect(orionUnit.priceFeed.api).toBe(orionPriceFeedAPI + '/price-feed'); diff --git a/src/crypt/signCFDOrder.ts b/src/crypt/signCFDOrder.ts index 3c8ed18..554ee39 100644 --- a/src/crypt/signCFDOrder.ts +++ b/src/crypt/signCFDOrder.ts @@ -1,4 +1,3 @@ -/* eslint-disable no-underscore-dangle */ import { type TypedDataSigner } from '@ethersproject/abstract-signer'; import BigNumber from 'bignumber.js'; import { type ethers } from 'ethers'; @@ -69,7 +68,7 @@ export const signCFDOrder = async ( // "Signature's v was always send as 27 or 28, but from Ledger was 0 or 1" const fixedSignature = joinSignature(splitSignature(signature)); - if (!fixedSignature) throw new Error("Can't sign order"); + // if (!fixedSignature) throw new Error("Can't sign order"); const signedOrder: SignedCFDOrder = { ...order, diff --git a/src/crypt/signCancelOrder.ts b/src/crypt/signCancelOrder.ts index 1dbbf0b..10cb6a6 100644 --- a/src/crypt/signCancelOrder.ts +++ b/src/crypt/signCancelOrder.ts @@ -1,4 +1,3 @@ -/* eslint-disable no-underscore-dangle */ import { type TypedDataSigner } from '@ethersproject/abstract-signer'; import { type ethers } from 'ethers'; import { joinSignature, splitSignature } from 'ethers/lib/utils'; @@ -37,7 +36,7 @@ const signCancelOrder = async ( // "Signature's v was always send as 27 or 28, but from Ledger was 0 or 1" const fixedSignature = joinSignature(splitSignature(signature)); - if (!fixedSignature) throw new Error("Can't sign order cancel"); + // if (!fixedSignature) throw new Error("Can't sign order cancel"); const signedCancelOrderReqeust: SignedCancelOrderRequest = { ...cancelOrderRequest, diff --git a/src/crypt/signOrder.ts b/src/crypt/signOrder.ts index af0427e..983e480 100644 --- a/src/crypt/signOrder.ts +++ b/src/crypt/signOrder.ts @@ -1,4 +1,3 @@ -/* eslint-disable no-underscore-dangle */ import { type TypedDataSigner } from '@ethersproject/abstract-signer'; import BigNumber from 'bignumber.js'; import { type ethers } from 'ethers'; @@ -74,7 +73,7 @@ export const signOrder = async ( // "Signature's v was always send as 27 or 28, but from Ledger was 0 or 1" const fixedSignature = joinSignature(splitSignature(signature)); - if (!fixedSignature) throw new Error("Can't sign order"); + // if (!fixedSignature) throw new Error("Can't sign order"); const signedOrder: SignedOrder = { ...order, diff --git a/src/utils/checkIsToken.ts b/src/utils/checkIsToken.ts index 43aa6c3..dca4156 100644 --- a/src/utils/checkIsToken.ts +++ b/src/utils/checkIsToken.ts @@ -1,4 +1,3 @@ -/* eslint-disable camelcase */ import { ERC20__factory } from '@orionprotocol/contracts'; import { ethers } from 'ethers'; import invariant from 'tiny-invariant'; diff --git a/src/utils/getBalance.ts b/src/utils/getBalance.ts index d34d855..b1a2469 100644 --- a/src/utils/getBalance.ts +++ b/src/utils/getBalance.ts @@ -2,9 +2,9 @@ import { ERC20__factory, type Exchange } from '@orionprotocol/contracts'; import type BigNumber from 'bignumber.js'; import { ethers } from 'ethers'; -import { utils } from '..'; import { INTERNAL_ORION_PRECISION, NATIVE_CURRENCY_PRECISION } from '../constants'; import { type OrionAggregator } from '../services/OrionAggregator'; +import denormalizeNumber from './denormalizeNumber'; export default async function getBalance( orionAggregator: OrionAggregator, @@ -25,13 +25,13 @@ export default async function getBalance( const assetDecimals = await assetContract.decimals(); assetWalletBalance = await assetContract.balanceOf(walletAddress); - denormalizedAssetInWalletBalance = utils.denormalizeNumber(assetWalletBalance, assetDecimals); + denormalizedAssetInWalletBalance = denormalizeNumber(assetWalletBalance, assetDecimals); } else { assetWalletBalance = await provider.getBalance(walletAddress); - denormalizedAssetInWalletBalance = utils.denormalizeNumber(assetWalletBalance, NATIVE_CURRENCY_PRECISION); + denormalizedAssetInWalletBalance = denormalizeNumber(assetWalletBalance, NATIVE_CURRENCY_PRECISION); } const assetContractBalance = await exchangeContract.getBalance(assetAddress, walletAddress); - const denormalizedAssetInContractBalance = utils.denormalizeNumber(assetContractBalance, INTERNAL_ORION_PRECISION); + const denormalizedAssetInContractBalance = denormalizeNumber(assetContractBalance, INTERNAL_ORION_PRECISION); const denormalizedAssetLockedBalanceResult = await orionAggregator.getLockedBalance(walletAddress, asset); if (denormalizedAssetLockedBalanceResult.isErr()) { throw new Error(denormalizedAssetLockedBalanceResult.error.message); diff --git a/src/utils/getNativeCryptocurrency.ts b/src/utils/getNativeCryptocurrency.ts index 47a4570..831ab7d 100644 --- a/src/utils/getNativeCryptocurrency.ts +++ b/src/utils/getNativeCryptocurrency.ts @@ -4,12 +4,12 @@ const getNativeCryptocurrency = (assetToAddress: Partial> const addressToAsset = Object .entries(assetToAddress) .reduce>>((prev, [asset, address]) => { - if (address === undefined) return prev; - return { - ...prev, - [address]: asset, - }; - }, {}); + if (address === undefined) return prev; + return { + ...prev, + [address]: asset, + }; + }, {}); const nativeCryptocurrency = addressToAsset[ethers.constants.AddressZero]; if (nativeCryptocurrency === undefined) throw new Error('Native cryptocurrency asset is not found'); diff --git a/src/utils/index.ts b/src/utils/index.ts index a0a178b..93c2948 100644 --- a/src/utils/index.ts +++ b/src/utils/index.ts @@ -12,6 +12,7 @@ export { default as parseExchangeTradeTransaction } from './parseExchangeTradeTr export { default as toUpperCase } from './toUpperCase'; export { default as toLowerCase } from './toLowerCase'; export { default as isUppercasedNetworkCode } from './isUppercasedNetworkCode'; +export { default as getNativeCryptocurrency } from './getNativeCryptocurrency'; // export { default as HttpError } from './httpError'; diff --git a/src/utils/objectKeys.ts b/src/utils/objectKeys.ts index b5a1514..6a5f17f 100644 --- a/src/utils/objectKeys.ts +++ b/src/utils/objectKeys.ts @@ -14,4 +14,4 @@ const untypedItems = Object.keys(items); // => Array @category Type guard */ // eslint-disable-next-line @typescript-eslint/consistent-type-assertions -export const objectKeys = Object.keys as (value: Type) => ObjectKeys[]; +export const objectKeys = Object.keys as (value: Type) => Array>;