This commit is contained in:
Aleksandr Kraiz
2023-02-13 18:13:30 +04:00
parent 9c9eeca555
commit 42e3e2a3eb
15 changed files with 56 additions and 50 deletions

View File

@@ -96,6 +96,8 @@ module.exports = {
2,
{
ignoreComments: true,
ignoreUrls: true,
ignoreTemplateLiterals: true,
}
],
'import/extensions': [

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -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');

View File

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

View File

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

View File

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

View File

@@ -1,4 +1,3 @@
/* eslint-disable camelcase */
import { ERC20__factory } from '@orionprotocol/contracts';
import { ethers } from 'ethers';
import invariant from 'tiny-invariant';

View File

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

View File

@@ -4,12 +4,12 @@ const getNativeCryptocurrency = (assetToAddress: Partial<Record<string, string>>
const addressToAsset = Object
.entries(assetToAddress)
.reduce<Partial<Record<string, string>>>((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');

View File

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

View File

@@ -14,4 +14,4 @@ const untypedItems = Object.keys(items); // => Array<string>
@category Type guard
*/
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions
export const objectKeys = Object.keys as <Type extends object>(value: Type) => ObjectKeys<Type>[];
export const objectKeys = Object.keys as <Type extends object>(value: Type) => Array<ObjectKeys<Type>>;