mirror of
https://github.com/orionprotocol/sdk.git
synced 2026-03-14 14:12:35 +03:00
Semantics improvements
This commit is contained in:
@@ -1,5 +1,5 @@
|
||||
import { ethers } from 'ethers';
|
||||
import type OrionUnit from '../../OrionUnit/index.js';
|
||||
import type Unit from '../../Unit/index.js';
|
||||
import type { SupportedChainId } from '../../types.js';
|
||||
import { isValidChainId } from '../../utils/index.js';
|
||||
import { simpleFetch } from 'simple-typed-fetch';
|
||||
@@ -7,18 +7,18 @@ import bsonObjectId from 'bson-objectid';
|
||||
|
||||
const ObjectID = bsonObjectId.default
|
||||
|
||||
const getHistory = async (units: OrionUnit[], address: string, limit = 1000) => {
|
||||
const getHistory = async (units: Unit[], address: string, limit = 1000) => {
|
||||
if (!ethers.utils.isAddress(address)) throw new Error(`Invalid address: ${address}`);
|
||||
const data = await Promise.all(units.map(async ({ orionBlockchain, orionAggregator, chainId }) => {
|
||||
const sourceNetworkHistory = await simpleFetch(orionBlockchain.getSourceAtomicSwapHistory)({
|
||||
const data = await Promise.all(units.map(async ({ blockchainService, aggregator, chainId }) => {
|
||||
const sourceNetworkHistory = await simpleFetch(blockchainService.getSourceAtomicSwapHistory)({
|
||||
limit,
|
||||
sender: address,
|
||||
});
|
||||
const targetNetworkHistory = await simpleFetch(orionBlockchain.getTargetAtomicSwapHistory)({
|
||||
const targetNetworkHistory = await simpleFetch(blockchainService.getTargetAtomicSwapHistory)({
|
||||
limit,
|
||||
receiver: address,
|
||||
});
|
||||
const orionAggregatorHistoryAtomicSwaps = await simpleFetch(orionAggregator.getHistoryAtomicSwaps)(
|
||||
const aggregatorHistoryAtomicSwaps = await simpleFetch(aggregator.getHistoryAtomicSwaps)(
|
||||
address,
|
||||
limit
|
||||
);
|
||||
@@ -62,12 +62,12 @@ const getHistory = async (units: OrionUnit[], address: string, limit = 1000) =>
|
||||
return acc;
|
||||
}, {});
|
||||
|
||||
type OrionAggregatorHistoryAtomicSwapsItem = typeof orionAggregatorHistoryAtomicSwaps[number] & {
|
||||
type AggregatorHistoryAtomicSwapsItem = typeof aggregatorHistoryAtomicSwaps[number] & {
|
||||
chainId: SupportedChainId
|
||||
}
|
||||
|
||||
const orionAggregatorHistoryAtomicSwapsObj = orionAggregatorHistoryAtomicSwaps.reduce<
|
||||
Partial<Record<string, OrionAggregatorHistoryAtomicSwapsItem>>
|
||||
const aggregatorHistoryAtomicSwapsObj = aggregatorHistoryAtomicSwaps.reduce<
|
||||
Partial<Record<string, AggregatorHistoryAtomicSwapsItem>>
|
||||
>((acc, cur) => {
|
||||
const { secretHash } = cur.lockOrder;
|
||||
const lowercaseSecretHash = secretHash.toLowerCase();
|
||||
@@ -82,7 +82,7 @@ const getHistory = async (units: OrionUnit[], address: string, limit = 1000) =>
|
||||
sourceNetworkHistory: sourceNetworkHistoryObj,
|
||||
targetNetworkHistory: targetNetworkHistoryObj,
|
||||
network: chainId,
|
||||
orionAggregatorHistoryAtomicSwaps: orionAggregatorHistoryAtomicSwapsObj
|
||||
aggregatorHistoryAtomicSwaps: aggregatorHistoryAtomicSwapsObj
|
||||
};
|
||||
}));
|
||||
|
||||
@@ -106,13 +106,13 @@ const getHistory = async (units: OrionUnit[], address: string, limit = 1000) =>
|
||||
}
|
||||
}, {});
|
||||
|
||||
type AggItems = typeof data[number]['orionAggregatorHistoryAtomicSwaps'];
|
||||
type AggItems = typeof data[number]['aggregatorHistoryAtomicSwaps'];
|
||||
|
||||
const unitedAggregatorHistory = data.reduce<AggItems>((acc, cur) => {
|
||||
const { orionAggregatorHistoryAtomicSwaps } = cur;
|
||||
const { aggregatorHistoryAtomicSwaps } = cur;
|
||||
return {
|
||||
...acc,
|
||||
...orionAggregatorHistoryAtomicSwaps,
|
||||
...aggregatorHistoryAtomicSwaps,
|
||||
}
|
||||
}, {});
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@ import getBalances from '../../utils/getBalances.js';
|
||||
import BalanceGuard from '../../BalanceGuard.js';
|
||||
import getAvailableSources from '../../utils/getAvailableFundsSources.js';
|
||||
import {
|
||||
INTERNAL_ORION_PRECISION,
|
||||
INTERNAL_PROTOCOL_PRECISION,
|
||||
NATIVE_CURRENCY_PRECISION,
|
||||
LOCKATOMIC_GAS_LIMIT,
|
||||
REDEEMATOMIC_GAS_LIMIT,
|
||||
@@ -16,7 +16,7 @@ import { denormalizeNumber, generateSecret, normalizeNumber, toUpperCase } from
|
||||
import type { SupportedChainId } from '../../types.js';
|
||||
import type Orion from '../index.js';
|
||||
import type { z } from 'zod';
|
||||
import type { placeAtomicSwapSchema } from '../../services/OrionAggregator/schemas/index.js';
|
||||
import type { placeAtomicSwapSchema } from '../../services/Aggregator/schemas/index.js';
|
||||
import { simpleFetch } from 'simple-typed-fetch';
|
||||
|
||||
type Params = {
|
||||
@@ -50,24 +50,24 @@ export default async function swap({
|
||||
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 sourceChainOrionUnit = orion.getUnit(sourceChain);
|
||||
const targetChainOrionUnit = orion.getUnit(targetChain);
|
||||
const sourceChainUnit = orion.getUnit(sourceChain);
|
||||
const targetChainUnit = orion.getUnit(targetChain);
|
||||
|
||||
const {
|
||||
orionBlockchain: sourceOrionBlockchain,
|
||||
orionAggregator: sourceOrionAggregator,
|
||||
blockchainService: sourceBlockchainService,
|
||||
aggregator: sourceAggregator,
|
||||
provider: sourceProvider,
|
||||
chainId,
|
||||
} = sourceChainOrionUnit;
|
||||
} = sourceChainUnit;
|
||||
|
||||
const {
|
||||
orionAggregator: targetOrionAggregator,
|
||||
orionBlockchain: targetOrionBlockchain,
|
||||
aggregator: targetAggregator,
|
||||
blockchainService: targetBlockchainService,
|
||||
provider: targetProvider,
|
||||
} = targetChainOrionUnit;
|
||||
} = targetChainUnit;
|
||||
|
||||
const sourceSupportedBridgeAssets = await simpleFetch(sourceOrionBlockchain.getAtomicSwapAssets)();
|
||||
const targetSupportedBridgeAssets = await simpleFetch(targetOrionBlockchain.getAtomicSwapAssets)();
|
||||
const sourceSupportedBridgeAssets = await simpleFetch(sourceBlockchainService.getAtomicSwapAssets)();
|
||||
const targetSupportedBridgeAssets = await simpleFetch(targetBlockchainService.getAtomicSwapAssets)();
|
||||
|
||||
const commonSupportedBridgeAssets = sourceSupportedBridgeAssets.filter((asset) => targetSupportedBridgeAssets.includes(asset));
|
||||
if (!sourceSupportedBridgeAssets.includes(assetName) || !targetSupportedBridgeAssets.includes(assetName)) {
|
||||
@@ -78,10 +78,10 @@ export default async function swap({
|
||||
const timeout = setTimeout(() => {
|
||||
reject(new Error("Can't get brokers balances. Timeout"));
|
||||
}, 10000);
|
||||
const id = targetOrionAggregator.ws.subscribe('btasabus', {
|
||||
const id = targetAggregator.ws.subscribe('btasabus', {
|
||||
callback: (data) => {
|
||||
targetOrionAggregator.ws.unsubscribe(id);
|
||||
targetOrionAggregator.ws.destroy();
|
||||
targetAggregator.ws.unsubscribe(id);
|
||||
targetAggregator.ws.destroy();
|
||||
clearTimeout(timeout);
|
||||
resolve(data);
|
||||
}
|
||||
@@ -98,11 +98,11 @@ export default async function swap({
|
||||
const {
|
||||
exchangeContractAddress: sourceExchangeContractAddress,
|
||||
assetToAddress: sourceAssetToAddress,
|
||||
} = await simpleFetch(sourceOrionBlockchain.getInfo)();
|
||||
} = await simpleFetch(sourceBlockchainService.getInfo)();
|
||||
|
||||
const sourceChainNativeCryptocurrency = getNativeCryptocurrencyName(sourceAssetToAddress);
|
||||
const sourceExchangeContract = Exchange__factory.connect(sourceExchangeContractAddress, sourceProvider);
|
||||
// const sourceChainGasPriceWei = await simpleFetch(sourceOrionBlockchain.getGasPriceWei)();
|
||||
// const sourceChainGasPriceWei = await simpleFetch(sourceBlockchainService.getGasPriceWei)();
|
||||
|
||||
const sourceChainAssetAddress = sourceAssetToAddress[assetName];
|
||||
if (sourceChainAssetAddress === undefined) throw new Error(`Asset '${assetName}' not found in source chain`);
|
||||
@@ -110,7 +110,7 @@ export default async function swap({
|
||||
const {
|
||||
exchangeContractAddress: targetExchangeContractAddress,
|
||||
assetToAddress: targetAssetToAddress,
|
||||
} = await simpleFetch(targetOrionBlockchain.getInfo)();
|
||||
} = await simpleFetch(targetBlockchainService.getInfo)();
|
||||
|
||||
const targetChainAssetAddress = targetAssetToAddress[assetName];
|
||||
if (targetChainAssetAddress === undefined) throw new Error(`Asset '${assetName}' not found in target chain`);
|
||||
@@ -122,7 +122,7 @@ export default async function swap({
|
||||
[assetName]: sourceChainAssetAddress,
|
||||
[sourceChainNativeCryptocurrency]: ethers.constants.AddressZero,
|
||||
},
|
||||
sourceOrionAggregator,
|
||||
sourceAggregator,
|
||||
walletAddress,
|
||||
sourceExchangeContract,
|
||||
sourceProvider,
|
||||
@@ -133,7 +133,7 @@ export default async function swap({
|
||||
[assetName]: targetChainAssetAddress,
|
||||
[targetChainNativeCryptocurrency]: ethers.constants.AddressZero,
|
||||
},
|
||||
targetOrionAggregator,
|
||||
targetAggregator,
|
||||
walletAddress,
|
||||
targetExchangeContract,
|
||||
targetProvider,
|
||||
@@ -169,12 +169,12 @@ export default async function swap({
|
||||
},
|
||||
amount: amountBN.toString(),
|
||||
spenderAddress: sourceExchangeContractAddress,
|
||||
sources: getAvailableSources('amount', sourceChainAssetAddress, 'orion_pool'),
|
||||
sources: getAvailableSources('amount', sourceChainAssetAddress, 'pool'),
|
||||
});
|
||||
|
||||
const amountBlockchainParam = normalizeNumber(
|
||||
amount,
|
||||
INTERNAL_ORION_PRECISION,
|
||||
INTERNAL_PROTOCOL_PRECISION,
|
||||
BigNumber.ROUND_FLOOR,
|
||||
);
|
||||
const secret = generateSecret();
|
||||
@@ -198,7 +198,7 @@ export default async function swap({
|
||||
});
|
||||
|
||||
let sourceChainGasPrice: ethers.BigNumber;
|
||||
const sourceChainFeeData = await sourceChainOrionUnit.provider.getFeeData();
|
||||
const sourceChainFeeData = await sourceChainUnit.provider.getFeeData();
|
||||
if (ethers.BigNumber.isBigNumber(sourceChainFeeData.gasPrice)) { //
|
||||
unsignedLockAtomicTx.gasPrice = sourceChainFeeData.gasPrice;
|
||||
sourceChainGasPrice = sourceChainFeeData.gasPrice;
|
||||
@@ -223,7 +223,7 @@ export default async function swap({
|
||||
value = amountBN.minus(denormalizedAssetInExchangeBalance);
|
||||
}
|
||||
unsignedLockAtomicTx.value = normalizeNumber(
|
||||
value.dp(INTERNAL_ORION_PRECISION, BigNumber.ROUND_CEIL),
|
||||
value.dp(INTERNAL_PROTOCOL_PRECISION, BigNumber.ROUND_CEIL),
|
||||
NATIVE_CURRENCY_PRECISION,
|
||||
BigNumber.ROUND_CEIL,
|
||||
);
|
||||
@@ -249,16 +249,16 @@ export default async function swap({
|
||||
|
||||
options?.logger?.('Signing lock tx transaction...');
|
||||
const signedTransaction = await signer.signTransaction(unsignedLockAtomicTx);
|
||||
const lockAtomicTxResponse = await sourceChainOrionUnit.provider.sendTransaction(signedTransaction);
|
||||
const lockAtomicTxResponse = await sourceChainUnit.provider.sendTransaction(signedTransaction);
|
||||
options?.logger?.(`Lock tx sent. Tx hash: ${lockAtomicTxResponse.hash}. Waiting for tx to be mined...`);
|
||||
await lockAtomicTxResponse.wait();
|
||||
options?.logger?.('Lock tx mined.');
|
||||
options?.logger?.('Placing atomic swap...');
|
||||
|
||||
const atomicSwap = await new Promise<z.infer<typeof placeAtomicSwapSchema>>((resolve, reject) => {
|
||||
const placeAtomicSwap = () => simpleFetch(targetOrionAggregator.placeAtomicSwap)(
|
||||
const placeAtomicSwap = () => simpleFetch(targetAggregator.placeAtomicSwap)(
|
||||
secretHash,
|
||||
toUpperCase(sourceChainOrionUnit.networkCode)
|
||||
toUpperCase(sourceChainUnit.networkCode)
|
||||
).then((data) => {
|
||||
clearInterval(interval);
|
||||
clearTimeout(timeout);
|
||||
@@ -276,7 +276,7 @@ export default async function swap({
|
||||
|
||||
options?.logger?.('Atomic swap placed.');
|
||||
|
||||
// const targetChainGasPriceWei = await simpleFetch(targetOrionBlockchain.getGasPriceWei)();
|
||||
// const targetChainGasPriceWei = await simpleFetch(targetBlockchainService.getGasPriceWei)();
|
||||
const unsignedRedeemAtomicTx = await targetExchangeContract.populateTransaction.redeemAtomic(
|
||||
{
|
||||
amount: amountBlockchainParam,
|
||||
@@ -292,7 +292,7 @@ export default async function swap({
|
||||
)
|
||||
|
||||
let targetChainGasPrice: ethers.BigNumber;
|
||||
const targetChainFeeData = await targetChainOrionUnit.provider.getFeeData();
|
||||
const targetChainFeeData = await targetChainUnit.provider.getFeeData();
|
||||
if (ethers.BigNumber.isBigNumber(targetChainFeeData.gasPrice)) { //
|
||||
unsignedRedeemAtomicTx.gasPrice = targetChainFeeData.gasPrice;
|
||||
targetChainGasPrice = targetChainFeeData.gasPrice;
|
||||
@@ -331,7 +331,7 @@ export default async function swap({
|
||||
options?.logger?.('Signing redeem tx transaction...');
|
||||
|
||||
const targetSignedTransaction = await signer.signTransaction(unsignedRedeemAtomicTx);
|
||||
const targetLockAtomicTxResponse = await targetChainOrionUnit.provider.sendTransaction(targetSignedTransaction);
|
||||
const targetLockAtomicTxResponse = await targetChainUnit.provider.sendTransaction(targetSignedTransaction);
|
||||
options?.logger?.(`Redeem tx sent. Tx hash: ${targetLockAtomicTxResponse.hash}. Waiting for tx to be mined...`);
|
||||
|
||||
await targetLockAtomicTxResponse.wait();
|
||||
|
||||
@@ -3,9 +3,9 @@ import type { ethers } from 'ethers';
|
||||
import { merge } from 'merge-anything';
|
||||
import { chains, envs } from '../config/index.js';
|
||||
import type { networkCodes } from '../constants/index.js';
|
||||
import OrionUnit from '../OrionUnit/index.js';
|
||||
import Unit from '../Unit/index.js';
|
||||
import { ReferralSystem } from '../services/ReferralSystem/index.js';
|
||||
import type { SupportedChainId, DeepPartial, VerboseOrionUnitConfig, KnownEnv } from '../types.js';
|
||||
import type { SupportedChainId, DeepPartial, VerboseUnitConfig, KnownEnv } from '../types.js';
|
||||
import { isValidChainId } from '../utils/index.js';
|
||||
import swap from './bridge/swap.js';
|
||||
import getHistory from './bridge/getHistory.js';
|
||||
@@ -17,7 +17,7 @@ type EnvConfig = {
|
||||
networks: Partial<
|
||||
Record<
|
||||
SupportedChainId,
|
||||
VerboseOrionUnitConfig
|
||||
VerboseUnitConfig
|
||||
>
|
||||
>
|
||||
}
|
||||
@@ -35,7 +35,7 @@ type AggregatedAssets = Partial<
|
||||
export default class Orion {
|
||||
public readonly env?: string;
|
||||
|
||||
public readonly units: Partial<Record<SupportedChainId, OrionUnit>>;
|
||||
public readonly units: Partial<Record<SupportedChainId, Unit>>;
|
||||
|
||||
public readonly referralSystem: ReferralSystem;
|
||||
|
||||
@@ -43,8 +43,6 @@ export default class Orion {
|
||||
|
||||
// TODO: get tradable pairs (aggregated)
|
||||
|
||||
// TODO: bridge
|
||||
|
||||
constructor(
|
||||
envOrConfig: KnownEnv | EnvConfig = 'production',
|
||||
overrides?: DeepPartial<EnvConfig>
|
||||
@@ -72,10 +70,10 @@ export default class Orion {
|
||||
api: networkConfig.api,
|
||||
nodeJsonRpc: networkConfig.rpc ?? chainConfig.rpc,
|
||||
services: {
|
||||
orionBlockchain: {
|
||||
blockchainService: {
|
||||
http: networkConfig.api + networkConfig.services.blockchain.http,
|
||||
},
|
||||
orionAggregator: {
|
||||
aggregator: {
|
||||
http: networkConfig.api + networkConfig.services.aggregator.http,
|
||||
ws: networkConfig.api + networkConfig.services.aggregator.ws,
|
||||
},
|
||||
@@ -85,7 +83,7 @@ export default class Orion {
|
||||
},
|
||||
};
|
||||
})
|
||||
.reduce<Partial<Record<SupportedChainId, VerboseOrionUnitConfig>>>((acc, cur) => {
|
||||
.reduce<Partial<Record<SupportedChainId, VerboseUnitConfig>>>((acc, cur) => {
|
||||
acc[cur.chainId] = cur;
|
||||
return acc;
|
||||
}, {}),
|
||||
@@ -102,12 +100,12 @@ export default class Orion {
|
||||
this.referralSystem = new ReferralSystem(config.referralAPI);
|
||||
|
||||
this.units = Object.entries(config.networks)
|
||||
.reduce<Partial<Record<SupportedChainId, OrionUnit>>>((acc, [chainId, networkConfig]) => {
|
||||
.reduce<Partial<Record<SupportedChainId, Unit>>>((acc, [chainId, networkConfig]) => {
|
||||
if (!isValidChainId(chainId)) throw new Error(`Invalid chainId: ${chainId}`);
|
||||
const chainConfig = chains[chainId];
|
||||
if (!chainConfig) throw new Error(`Chain config not found: ${chainId}`);
|
||||
|
||||
const orionUnit = new OrionUnit({
|
||||
const unit = new Unit({
|
||||
// env: networkConfig.env,
|
||||
chainId,
|
||||
// api: networkConfig.api,
|
||||
@@ -116,7 +114,7 @@ export default class Orion {
|
||||
});
|
||||
return {
|
||||
...acc,
|
||||
[chainId]: orionUnit,
|
||||
[chainId]: unit,
|
||||
}
|
||||
}, {});
|
||||
}
|
||||
@@ -125,8 +123,8 @@ export default class Orion {
|
||||
return Object.entries(this.units).map(([, unit]) => unit);
|
||||
}
|
||||
|
||||
getUnit(networkCodeOrChainId: typeof networkCodes[number] | SupportedChainId): OrionUnit {
|
||||
let unit: OrionUnit | undefined;
|
||||
getUnit(networkCodeOrChainId: typeof networkCodes[number] | SupportedChainId): Unit {
|
||||
let unit: Unit | undefined;
|
||||
if (isValidChainId(networkCodeOrChainId)) {
|
||||
unit = this.units[networkCodeOrChainId];
|
||||
} else {
|
||||
@@ -148,7 +146,7 @@ export default class Orion {
|
||||
const aggregatedAssets: AggregatedAssets = {};
|
||||
|
||||
await Promise.all(this.unitsArray.map(async (unit) => {
|
||||
const { assetToAddress } = await simpleFetch(unit.orionBlockchain.getInfo)();
|
||||
const { assetToAddress } = await simpleFetch(unit.blockchainService.getInfo)();
|
||||
Object.entries(assetToAddress).forEach(([asset, address]) => {
|
||||
if (address === undefined) throw new Error(`Address is undefined for asset: ${asset}`);
|
||||
aggregatedAssets[asset] = {
|
||||
@@ -172,7 +170,7 @@ export default class Orion {
|
||||
if (aggregatedBaseAsset === undefined) {
|
||||
const networks = chainIds.map((chainId) => chains[chainId]?.label).join(', ');
|
||||
console.error(
|
||||
`Asset found in Aggregator, but not in Orion Blockchain (base): ${baseAsset} (${pair}).` +
|
||||
`Asset found in Aggregator, but not in BlockchainService (base): ${baseAsset} (${pair}).` +
|
||||
` Networks: ${networks}`
|
||||
);
|
||||
} else {
|
||||
@@ -182,7 +180,7 @@ export default class Orion {
|
||||
if (aggregatedQuoteAsset === undefined) {
|
||||
const networks = chainIds.map((chainId) => chains[chainId]?.label).join(', ');
|
||||
console.error(
|
||||
`Asset found in Aggregator, but not in OrionBlockchain (quote): ${quoteAsset} (${pair}).` +
|
||||
`Asset found in Aggregator, but not in BlockchainService (quote): ${quoteAsset} (${pair}).` +
|
||||
` Networks: ${networks}`
|
||||
);
|
||||
} else {
|
||||
@@ -193,7 +191,7 @@ export default class Orion {
|
||||
return aggregatedAssets;
|
||||
}
|
||||
|
||||
async getPairs(...params: Parameters<OrionUnit['orionAggregator']['getPairsList']>) {
|
||||
async getPairs(...params: Parameters<Unit['aggregator']['getPairsList']>) {
|
||||
const result: Partial<
|
||||
Record<
|
||||
string,
|
||||
@@ -202,7 +200,7 @@ export default class Orion {
|
||||
> = {};
|
||||
|
||||
await Promise.all(this.unitsArray.map(async (unit) => {
|
||||
const pairs = await simpleFetch(unit.orionAggregator.getPairsList)(...params);
|
||||
const pairs = await simpleFetch(unit.aggregator.getPairsList)(...params);
|
||||
pairs.forEach((pair) => {
|
||||
result[pair] = [
|
||||
...(result[pair] ?? []),
|
||||
|
||||
@@ -3,9 +3,9 @@ import { ethers } from 'ethers';
|
||||
import { Exchange__factory } from '@orionprotocol/contracts/lib/ethers-v5/index.js';
|
||||
import getBalances from '../../utils/getBalances.js';
|
||||
import BalanceGuard from '../../BalanceGuard.js';
|
||||
import type OrionUnit from '../index.js';
|
||||
import type Unit from '../index.js';
|
||||
import {
|
||||
DEPOSIT_ERC20_GAS_LIMIT, DEPOSIT_ETH_GAS_LIMIT, INTERNAL_ORION_PRECISION, NATIVE_CURRENCY_PRECISION,
|
||||
DEPOSIT_ERC20_GAS_LIMIT, DEPOSIT_ETH_GAS_LIMIT, INTERNAL_PROTOCOL_PRECISION, NATIVE_CURRENCY_PRECISION,
|
||||
} from '../../constants/index.js';
|
||||
import { denormalizeNumber, normalizeNumber } from '../../utils/index.js';
|
||||
import getNativeCryptocurrencyName from '../../utils/getNativeCryptocurrencyName.js';
|
||||
@@ -15,14 +15,14 @@ export type DepositParams = {
|
||||
asset: string
|
||||
amount: BigNumber.Value
|
||||
signer: ethers.Signer
|
||||
orionUnit: OrionUnit
|
||||
unit: Unit
|
||||
}
|
||||
|
||||
export default async function deposit({
|
||||
asset,
|
||||
amount,
|
||||
signer,
|
||||
orionUnit,
|
||||
unit,
|
||||
}: DepositParams) {
|
||||
if (asset === '') throw new Error('Asset can not be empty');
|
||||
|
||||
@@ -33,17 +33,17 @@ export default async function deposit({
|
||||
const walletAddress = await signer.getAddress();
|
||||
|
||||
const {
|
||||
orionBlockchain, orionAggregator, provider, chainId,
|
||||
} = orionUnit;
|
||||
blockchainService, aggregator, provider, chainId,
|
||||
} = unit;
|
||||
const {
|
||||
exchangeContractAddress,
|
||||
assetToAddress,
|
||||
} = await simpleFetch(orionBlockchain.getInfo)();
|
||||
} = await simpleFetch(blockchainService.getInfo)();
|
||||
|
||||
const nativeCryptocurrency = getNativeCryptocurrencyName(assetToAddress);
|
||||
|
||||
const exchangeContract = Exchange__factory.connect(exchangeContractAddress, provider);
|
||||
const gasPriceWei = await simpleFetch(orionBlockchain.getGasPriceWei)();
|
||||
const gasPriceWei = await simpleFetch(blockchainService.getGasPriceWei)();
|
||||
|
||||
const assetAddress = assetToAddress[asset];
|
||||
if (assetAddress === undefined) throw new Error(`Asset '${asset}' not found`);
|
||||
@@ -53,7 +53,7 @@ export default async function deposit({
|
||||
[asset]: assetAddress,
|
||||
[nativeCryptocurrency]: ethers.constants.AddressZero,
|
||||
},
|
||||
orionAggregator,
|
||||
aggregator,
|
||||
walletAddress,
|
||||
exchangeContract,
|
||||
provider,
|
||||
@@ -88,7 +88,7 @@ export default async function deposit({
|
||||
} else {
|
||||
unsignedTx = await exchangeContract.populateTransaction.depositAsset(
|
||||
assetAddress,
|
||||
normalizeNumber(amount, INTERNAL_ORION_PRECISION, BigNumber.ROUND_CEIL),
|
||||
normalizeNumber(amount, INTERNAL_PROTOCOL_PRECISION, BigNumber.ROUND_CEIL),
|
||||
);
|
||||
unsignedTx.gasLimit = ethers.BigNumber.from(DEPOSIT_ERC20_GAS_LIMIT);
|
||||
}
|
||||
@@ -2,8 +2,8 @@ import { BigNumber } from 'bignumber.js';
|
||||
import { ethers } from 'ethers';
|
||||
import { simpleFetch } from 'simple-typed-fetch';
|
||||
import { NATIVE_CURRENCY_PRECISION, SWAP_THROUGH_ORION_POOL_GAS_LIMIT } from '../../constants/index.js';
|
||||
import type { OrionAggregator } from '../../services/OrionAggregator/index.js';
|
||||
import type { OrionBlockchain } from '../../services/OrionBlockchain/index.js';
|
||||
import type { Aggregator } from '../../services/Aggregator/index.js';
|
||||
import type { BlockchainService } from '../../services/BlockchainService/index.js';
|
||||
|
||||
import { calculateFeeInFeeAsset, denormalizeNumber, getNativeCryptocurrencyName } from '../../utils/index.js';
|
||||
|
||||
@@ -13,8 +13,8 @@ export type GetSwapInfoParams = {
|
||||
assetOut: string
|
||||
amount: BigNumber.Value
|
||||
feeAsset: string
|
||||
orionBlockchain: OrionBlockchain
|
||||
orionAggregator: OrionAggregator
|
||||
blockchainService: BlockchainService
|
||||
aggregator: Aggregator
|
||||
options?: {
|
||||
instantSettlement?: boolean
|
||||
poolOnly?: boolean
|
||||
@@ -27,8 +27,8 @@ export default async function getSwapInfo({
|
||||
assetOut,
|
||||
amount,
|
||||
feeAsset,
|
||||
orionBlockchain,
|
||||
orionAggregator,
|
||||
blockchainService,
|
||||
aggregator,
|
||||
options,
|
||||
}: GetSwapInfoParams) {
|
||||
if (amount === '') throw new Error('Amount can not be empty');
|
||||
@@ -42,12 +42,12 @@ export default async function getSwapInfo({
|
||||
|
||||
const {
|
||||
assetToAddress,
|
||||
} = await simpleFetch(orionBlockchain.getInfo)();
|
||||
} = await simpleFetch(blockchainService.getInfo)();
|
||||
const nativeCryptocurrencyName = getNativeCryptocurrencyName(assetToAddress);
|
||||
|
||||
const feeAssets = await simpleFetch(orionBlockchain.getTokensFee)();
|
||||
const pricesInOrn = await simpleFetch(orionBlockchain.getPrices)();
|
||||
const gasPriceWei = await simpleFetch(orionBlockchain.getGasPriceWei)();
|
||||
const feeAssets = await simpleFetch(blockchainService.getTokensFee)();
|
||||
const pricesInOrn = await simpleFetch(blockchainService.getPrices)();
|
||||
const gasPriceWei = await simpleFetch(blockchainService.getGasPriceWei)();
|
||||
|
||||
const gasPriceGwei = ethers.utils.formatUnits(gasPriceWei, 'gwei').toString();
|
||||
|
||||
@@ -58,7 +58,7 @@ export default async function getSwapInfo({
|
||||
throw new Error(`Fee asset '${feeAsset}' not found. Available assets: ${Object.keys(feeAssets).join(', ')}`);
|
||||
}
|
||||
|
||||
const swapInfo = await simpleFetch(orionAggregator.getSwapInfo)(
|
||||
const swapInfo = await simpleFetch(aggregator.getSwapInfo)(
|
||||
type,
|
||||
assetIn,
|
||||
assetOut,
|
||||
@@ -70,7 +70,7 @@ export default async function getSwapInfo({
|
||||
);
|
||||
|
||||
const { exchanges: swapExchanges } = swapInfo;
|
||||
const { factories } = await simpleFetch(orionBlockchain.getPoolsConfig)();
|
||||
const { factories } = await simpleFetch(blockchainService.getPoolsConfig)();
|
||||
const poolExchangesList = factories !== undefined ? Object.keys(factories) : [];
|
||||
const [firstSwapExchange] = swapExchanges;
|
||||
|
||||
@@ -131,7 +131,7 @@ export default async function getSwapInfo({
|
||||
if (feePercent === undefined) throw new Error(`Fee asset ${feeAsset} not available`);
|
||||
|
||||
const {
|
||||
orionFeeInFeeAsset,
|
||||
serviceFeeInFeeAsset,
|
||||
networkFeeInFeeAsset,
|
||||
} = calculateFeeInFeeAsset(
|
||||
swapInfo.orderInfo.amount,
|
||||
@@ -149,7 +149,7 @@ export default async function getSwapInfo({
|
||||
assetName: feeAsset,
|
||||
assetAddress: feeAssetAddress,
|
||||
networkFeeInFeeAsset,
|
||||
protocolFeeInFeeAsset: orionFeeInFeeAsset,
|
||||
protocolFeeInFeeAsset: serviceFeeInFeeAsset,
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import type OrionUnit from '../index.js';
|
||||
import type Unit from '../index.js';
|
||||
import deposit, { type DepositParams } from './deposit.js';
|
||||
import getSwapInfo, { type GetSwapInfoParams } from './getSwapInfo.js';
|
||||
import type { SwapLimitParams } from './swapLimit.js';
|
||||
@@ -6,37 +6,37 @@ import swapLimit from './swapLimit.js';
|
||||
import swapMarket, { type SwapMarketParams } from './swapMarket.js';
|
||||
import withdraw, { type WithdrawParams } from './withdraw.js';
|
||||
|
||||
type PureSwapMarketParams = Omit<SwapMarketParams, 'orionUnit'>
|
||||
type PureSwapLimitParams = Omit<SwapLimitParams, 'orionUnit'>
|
||||
type PureDepositParams = Omit<DepositParams, 'orionUnit'>
|
||||
type PureWithdrawParams = Omit<WithdrawParams, 'orionUnit'>
|
||||
type PureGetSwapMarketInfoParams = Omit<GetSwapInfoParams, 'orionBlockchain' | 'orionAggregator'>
|
||||
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'>
|
||||
|
||||
export default class Exchange {
|
||||
private readonly orionUnit: OrionUnit;
|
||||
private readonly unit: Unit;
|
||||
|
||||
constructor(orionUnit: OrionUnit) {
|
||||
this.orionUnit = orionUnit;
|
||||
constructor(unit: Unit) {
|
||||
this.unit = unit;
|
||||
}
|
||||
|
||||
public swapLimit(params: PureSwapLimitParams) {
|
||||
return swapLimit({
|
||||
...params,
|
||||
orionUnit: this.orionUnit,
|
||||
unit: this.unit,
|
||||
});
|
||||
}
|
||||
|
||||
public swapMarket(params: PureSwapMarketParams) {
|
||||
return swapMarket({
|
||||
...params,
|
||||
orionUnit: this.orionUnit,
|
||||
unit: this.unit,
|
||||
});
|
||||
}
|
||||
|
||||
public getSwapInfo(params: PureGetSwapMarketInfoParams) {
|
||||
return getSwapInfo({
|
||||
orionAggregator: this.orionUnit.orionAggregator,
|
||||
orionBlockchain: this.orionUnit.orionBlockchain,
|
||||
aggregator: this.unit.aggregator,
|
||||
blockchainService: this.unit.blockchainService,
|
||||
...params,
|
||||
});
|
||||
}
|
||||
@@ -44,14 +44,14 @@ export default class Exchange {
|
||||
public deposit(params: PureDepositParams) {
|
||||
return deposit({
|
||||
...params,
|
||||
orionUnit: this.orionUnit,
|
||||
unit: this.unit,
|
||||
});
|
||||
}
|
||||
|
||||
public withdraw(params: PureWithdrawParams) {
|
||||
return withdraw({
|
||||
...params,
|
||||
orionUnit: this.orionUnit,
|
||||
unit: this.unit,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -4,12 +4,12 @@ import { Exchange__factory } from '@orionprotocol/contracts/lib/ethers-v5/index.
|
||||
import getBalances from '../../utils/getBalances.js';
|
||||
import BalanceGuard from '../../BalanceGuard.js';
|
||||
import getAvailableSources from '../../utils/getAvailableFundsSources.js';
|
||||
import type OrionUnit from '../index.js';
|
||||
import { INTERNAL_ORION_PRECISION, NATIVE_CURRENCY_PRECISION, SWAP_THROUGH_ORION_POOL_GAS_LIMIT } from '../../constants/index.js';
|
||||
import type Unit from '../index.js';
|
||||
import { INTERNAL_PROTOCOL_PRECISION, NATIVE_CURRENCY_PRECISION, SWAP_THROUGH_ORION_POOL_GAS_LIMIT } from '../../constants/index.js';
|
||||
import getNativeCryptocurrencyName from '../../utils/getNativeCryptocurrencyName.js';
|
||||
import { calculateFeeInFeeAsset, denormalizeNumber, normalizeNumber } from '../../utils/index.js';
|
||||
import { signOrder } from '../../crypt/index.js';
|
||||
import type orderSchema from '../../services/OrionAggregator/schemas/orderSchema.js';
|
||||
import type orderSchema from '../../services/Aggregator/schemas/orderSchema.js';
|
||||
import type { z } from 'zod';
|
||||
import { simpleFetch } from 'simple-typed-fetch';
|
||||
|
||||
@@ -21,7 +21,7 @@ export type SwapLimitParams = {
|
||||
amount: BigNumber.Value
|
||||
feeAsset: string
|
||||
signer: ethers.Signer
|
||||
orionUnit: OrionUnit
|
||||
unit: Unit
|
||||
options?: {
|
||||
poolOnly?: boolean
|
||||
instantSettlement?: boolean
|
||||
@@ -42,7 +42,7 @@ type AggregatorOrder = {
|
||||
|
||||
type PoolSwap = {
|
||||
amountOut: number
|
||||
through: 'orion_pool'
|
||||
through: 'pool'
|
||||
txHash: string
|
||||
wait: (confirmations?: number | undefined) => Promise<ethers.providers.TransactionReceipt>
|
||||
}
|
||||
@@ -57,7 +57,7 @@ export default async function swapLimit({
|
||||
amount,
|
||||
feeAsset,
|
||||
signer,
|
||||
orionUnit,
|
||||
unit,
|
||||
options,
|
||||
}: SwapLimitParams): Promise<Swap> {
|
||||
if (options?.developer) options.logger?.('YOU SPECIFIED A DEVELOPER OPTIONS. BE CAREFUL!');
|
||||
@@ -79,20 +79,20 @@ export default async function swapLimit({
|
||||
options?.logger?.(`Wallet address is ${walletAddress}`);
|
||||
|
||||
const {
|
||||
orionBlockchain, orionAggregator, provider, chainId,
|
||||
} = orionUnit;
|
||||
blockchainService, aggregator, provider, chainId,
|
||||
} = unit;
|
||||
const {
|
||||
exchangeContractAddress,
|
||||
matcherAddress,
|
||||
assetToAddress,
|
||||
} = await simpleFetch(orionBlockchain.getInfo)();
|
||||
} = await simpleFetch(blockchainService.getInfo)();
|
||||
const nativeCryptocurrency = getNativeCryptocurrencyName(assetToAddress);
|
||||
|
||||
const exchangeContract = Exchange__factory.connect(exchangeContractAddress, provider);
|
||||
const feeAssets = await simpleFetch(orionBlockchain.getTokensFee)();
|
||||
const pricesInOrn = await simpleFetch(orionBlockchain.getPrices)();
|
||||
const gasPriceWei = await simpleFetch(orionBlockchain.getGasPriceWei)();
|
||||
const { factories } = await simpleFetch(orionBlockchain.getPoolsConfig)();
|
||||
const feeAssets = await simpleFetch(blockchainService.getTokensFee)();
|
||||
const pricesInOrn = await simpleFetch(blockchainService.getPrices)();
|
||||
const gasPriceWei = await simpleFetch(blockchainService.getGasPriceWei)();
|
||||
const { factories } = await simpleFetch(blockchainService.getPoolsConfig)();
|
||||
const poolExchangesList = factories !== undefined ? Object.keys(factories) : [];
|
||||
|
||||
const gasPriceGwei = ethers.utils.formatUnits(gasPriceWei, 'gwei').toString();
|
||||
@@ -110,7 +110,7 @@ export default async function swapLimit({
|
||||
[feeAsset]: feeAssetAddress,
|
||||
[nativeCryptocurrency]: ethers.constants.AddressZero,
|
||||
},
|
||||
orionAggregator,
|
||||
aggregator,
|
||||
walletAddress,
|
||||
exchangeContract,
|
||||
provider,
|
||||
@@ -127,7 +127,7 @@ export default async function swapLimit({
|
||||
options?.logger,
|
||||
);
|
||||
|
||||
const swapInfo = await simpleFetch(orionAggregator.getSwapInfo)(
|
||||
const swapInfo = await simpleFetch(aggregator.getSwapInfo)(
|
||||
type,
|
||||
assetIn,
|
||||
assetOut,
|
||||
@@ -158,7 +158,7 @@ export default async function swapLimit({
|
||||
if (baseAssetName === undefined) throw new Error('Base asset name is undefined');
|
||||
if (quoteAssetName === undefined) throw new Error('Quote asset name is undefined');
|
||||
|
||||
const pairConfig = await simpleFetch(orionAggregator.getPairConfig)(`${baseAssetName}-${quoteAssetName}`);
|
||||
const pairConfig = await simpleFetch(aggregator.getPairConfig)(`${baseAssetName}-${quoteAssetName}`);
|
||||
const minQtyBN = new BigNumber(pairConfig.minQty);
|
||||
const qtyPrecisionBN = new BigNumber(pairConfig.qtyPrecision);
|
||||
const pricePrecisionBN = new BigNumber(pairConfig.pricePrecision);
|
||||
@@ -254,7 +254,7 @@ export default async function swapLimit({
|
||||
},
|
||||
amount: amountSpend.toString(),
|
||||
spenderAddress: exchangeContractAddress,
|
||||
sources: getAvailableSources('amount', assetInAddress, 'orion_pool'),
|
||||
sources: getAvailableSources('amount', assetInAddress, 'pool'),
|
||||
});
|
||||
|
||||
const amountReceive = swapInfo.type === 'exactReceive'
|
||||
@@ -262,12 +262,12 @@ export default async function swapLimit({
|
||||
: new BigNumber(swapInfo.orderInfo.amount).multipliedBy(swapInfo.orderInfo.safePrice)
|
||||
const amountSpendBlockchainParam = normalizeNumber(
|
||||
amountSpend,
|
||||
INTERNAL_ORION_PRECISION,
|
||||
INTERNAL_PROTOCOL_PRECISION,
|
||||
BigNumber.ROUND_CEIL,
|
||||
);
|
||||
const amountReceiveBlockchainParam = normalizeNumber(
|
||||
amountReceive,
|
||||
INTERNAL_ORION_PRECISION,
|
||||
INTERNAL_PROTOCOL_PRECISION,
|
||||
BigNumber.ROUND_FLOOR,
|
||||
);
|
||||
|
||||
@@ -293,7 +293,7 @@ export default async function swapLimit({
|
||||
value = amountSpendBN.minus(denormalizedAssetInExchangeBalance);
|
||||
}
|
||||
unsignedSwapThroughOrionPoolTx.value = normalizeNumber(
|
||||
value.dp(INTERNAL_ORION_PRECISION, BigNumber.ROUND_CEIL),
|
||||
value.dp(INTERNAL_PROTOCOL_PRECISION, BigNumber.ROUND_CEIL),
|
||||
NATIVE_CURRENCY_PRECISION,
|
||||
BigNumber.ROUND_CEIL,
|
||||
);
|
||||
@@ -309,7 +309,7 @@ export default async function swapLimit({
|
||||
address: ethers.constants.AddressZero,
|
||||
},
|
||||
amount: denormalizedTransactionCost.toString(),
|
||||
sources: getAvailableSources('network_fee', ethers.constants.AddressZero, 'orion_pool'),
|
||||
sources: getAvailableSources('network_fee', ethers.constants.AddressZero, 'pool'),
|
||||
});
|
||||
|
||||
// if (value.gt(0)) {
|
||||
@@ -320,7 +320,7 @@ export default async function swapLimit({
|
||||
// address: ethers.constants.AddressZero,
|
||||
// },
|
||||
// amount: value.toString(),
|
||||
// sources: getAvailableSources('amount', ethers.constants.AddressZero, 'orion_pool'),
|
||||
// sources: getAvailableSources('amount', ethers.constants.AddressZero, 'pool'),
|
||||
// });
|
||||
// }
|
||||
|
||||
@@ -335,7 +335,7 @@ export default async function swapLimit({
|
||||
return {
|
||||
amountOut: swapInfo.amountOut,
|
||||
wait: swapThroughOrionPoolTxResponse.wait,
|
||||
through: 'orion_pool',
|
||||
through: 'pool',
|
||||
txHash: swapThroughOrionPoolTxResponse.hash,
|
||||
};
|
||||
}
|
||||
@@ -381,7 +381,7 @@ export default async function swapLimit({
|
||||
const feePercent = feeAssets[feeAsset];
|
||||
if (feePercent === undefined) throw new Error(`Fee asset ${feeAsset} not available`);
|
||||
|
||||
const { orionFeeInFeeAsset, networkFeeInFeeAsset, totalFeeInFeeAsset } = calculateFeeInFeeAsset(
|
||||
const { serviceFeeInFeeAsset, networkFeeInFeeAsset, totalFeeInFeeAsset } = calculateFeeInFeeAsset(
|
||||
swapInfo.orderInfo.amount,
|
||||
feeAssetPriceInOrn,
|
||||
baseAssetPriceInOrn,
|
||||
@@ -414,9 +414,9 @@ export default async function swapLimit({
|
||||
name: feeAsset,
|
||||
address: feeAssetAddress,
|
||||
},
|
||||
amount: orionFeeInFeeAsset,
|
||||
amount: serviceFeeInFeeAsset,
|
||||
spenderAddress: exchangeContractAddress,
|
||||
sources: getAvailableSources('orion_fee', feeAssetAddress, 'aggregator'),
|
||||
sources: getAvailableSources('service_fee', feeAssetAddress, 'aggregator'),
|
||||
});
|
||||
|
||||
await balanceGuard.check(options?.autoApprove);
|
||||
@@ -438,7 +438,7 @@ export default async function swapLimit({
|
||||
const orderIsOk = await exchangeContract.validateOrder(signedOrder);
|
||||
if (!orderIsOk) throw new Error('Order is not valid');
|
||||
|
||||
const { orderId } = await simpleFetch(orionAggregator.placeOrder)(signedOrder, false);
|
||||
const { orderId } = await simpleFetch(aggregator.placeOrder)(signedOrder, false);
|
||||
options?.logger?.(`Order placed. Order id: ${orderId}`);
|
||||
|
||||
return {
|
||||
@@ -448,7 +448,7 @@ export default async function swapLimit({
|
||||
reject(new Error('Timeout'))
|
||||
}, 60000);
|
||||
const interval = setInterval(() => {
|
||||
simpleFetch(orionAggregator.getOrder)(orderId).then((data) => {
|
||||
simpleFetch(aggregator.getOrder)(orderId).then((data) => {
|
||||
if (data.order.status === 'SETTLED') {
|
||||
options?.logger?.(`Order ${orderId} settled`);
|
||||
clearTimeout(timeout);
|
||||
@@ -4,11 +4,11 @@ import { Exchange__factory } from '@orionprotocol/contracts/lib/ethers-v5/index.
|
||||
import getBalances from '../../utils/getBalances.js';
|
||||
import BalanceGuard from '../../BalanceGuard.js';
|
||||
import getAvailableSources from '../../utils/getAvailableFundsSources.js';
|
||||
import { INTERNAL_ORION_PRECISION, NATIVE_CURRENCY_PRECISION, SWAP_THROUGH_ORION_POOL_GAS_LIMIT } from '../../constants/index.js';
|
||||
import { INTERNAL_PROTOCOL_PRECISION, NATIVE_CURRENCY_PRECISION, SWAP_THROUGH_ORION_POOL_GAS_LIMIT } from '../../constants/index.js';
|
||||
import getNativeCryptocurrencyName from '../../utils/getNativeCryptocurrencyName.js';
|
||||
import { calculateFeeInFeeAsset, denormalizeNumber, normalizeNumber } from '../../utils/index.js';
|
||||
import { signOrder } from '../../crypt/index.js';
|
||||
import type orderSchema from '../../services/OrionAggregator/schemas/orderSchema.js';
|
||||
import type orderSchema from '../../services/Aggregator/schemas/orderSchema.js';
|
||||
import type { z } from 'zod';
|
||||
import type { SwapLimitParams } from './swapLimit.js';
|
||||
import { simpleFetch } from 'simple-typed-fetch';
|
||||
@@ -26,7 +26,7 @@ type AggregatorOrder = {
|
||||
|
||||
type PoolSwap = {
|
||||
amountOut: number
|
||||
through: 'orion_pool'
|
||||
through: 'pool'
|
||||
txHash: string
|
||||
wait: (confirmations?: number | undefined) => Promise<ethers.providers.TransactionReceipt>
|
||||
}
|
||||
@@ -41,7 +41,7 @@ export default async function swapMarket({
|
||||
feeAsset,
|
||||
slippagePercent,
|
||||
signer,
|
||||
orionUnit,
|
||||
unit,
|
||||
options,
|
||||
}: SwapMarketParams): Promise<Swap> {
|
||||
if (options?.developer) options.logger?.('YOU SPECIFIED A DEVELOPER OPTIONS. BE CAREFUL!');
|
||||
@@ -64,20 +64,20 @@ export default async function swapMarket({
|
||||
options?.logger?.(`Wallet address is ${walletAddress}`);
|
||||
|
||||
const {
|
||||
orionBlockchain, orionAggregator, provider, chainId,
|
||||
} = orionUnit;
|
||||
blockchainService, aggregator, provider, chainId,
|
||||
} = unit;
|
||||
const {
|
||||
exchangeContractAddress,
|
||||
matcherAddress,
|
||||
assetToAddress,
|
||||
} = await simpleFetch(orionBlockchain.getInfo)();
|
||||
} = await simpleFetch(blockchainService.getInfo)();
|
||||
const nativeCryptocurrency = getNativeCryptocurrencyName(assetToAddress);
|
||||
|
||||
const exchangeContract = Exchange__factory.connect(exchangeContractAddress, provider);
|
||||
const feeAssets = await simpleFetch(orionBlockchain.getTokensFee)();
|
||||
const pricesInOrn = await simpleFetch(orionBlockchain.getPrices)();
|
||||
const gasPriceWei = await simpleFetch(orionBlockchain.getGasPriceWei)();
|
||||
const { factories } = await simpleFetch(orionBlockchain.getPoolsConfig)();
|
||||
const feeAssets = await simpleFetch(blockchainService.getTokensFee)();
|
||||
const pricesInOrn = await simpleFetch(blockchainService.getPrices)();
|
||||
const gasPriceWei = await simpleFetch(blockchainService.getGasPriceWei)();
|
||||
const { factories } = await simpleFetch(blockchainService.getPoolsConfig)();
|
||||
const poolExchangesList = factories !== undefined ? Object.keys(factories) : [];
|
||||
|
||||
const gasPriceGwei = ethers.utils.formatUnits(gasPriceWei, 'gwei').toString();
|
||||
@@ -95,7 +95,7 @@ export default async function swapMarket({
|
||||
[feeAsset]: feeAssetAddress,
|
||||
[nativeCryptocurrency]: ethers.constants.AddressZero,
|
||||
},
|
||||
orionAggregator,
|
||||
aggregator,
|
||||
walletAddress,
|
||||
exchangeContract,
|
||||
provider,
|
||||
@@ -112,7 +112,7 @@ export default async function swapMarket({
|
||||
options?.logger,
|
||||
);
|
||||
|
||||
const swapInfo = await simpleFetch(orionAggregator.getSwapInfo)(
|
||||
const swapInfo = await simpleFetch(aggregator.getSwapInfo)(
|
||||
type,
|
||||
assetIn,
|
||||
assetOut,
|
||||
@@ -143,7 +143,7 @@ export default async function swapMarket({
|
||||
if (baseAssetName === undefined) throw new Error('Base asset name is undefined');
|
||||
if (quoteAssetName === undefined) throw new Error('Quote asset name is undefined');
|
||||
|
||||
const pairConfig = await simpleFetch(orionAggregator.getPairConfig)(`${baseAssetName}-${quoteAssetName}`);
|
||||
const pairConfig = await simpleFetch(aggregator.getPairConfig)(`${baseAssetName}-${quoteAssetName}`);
|
||||
const qtyPrecisionBN = new BigNumber(pairConfig.qtyPrecision);
|
||||
const qtyDecimalPlaces = amountBN.dp();
|
||||
|
||||
@@ -207,18 +207,18 @@ export default async function swapMarket({
|
||||
},
|
||||
amount: amountSpend.toString(),
|
||||
spenderAddress: exchangeContractAddress,
|
||||
sources: getAvailableSources('amount', assetInAddress, 'orion_pool'),
|
||||
sources: getAvailableSources('amount', assetInAddress, 'pool'),
|
||||
});
|
||||
|
||||
const amountReceive = swapInfo.type === 'exactReceive' ? swapInfo.amountOut : amountOutWithSlippage;
|
||||
const amountSpendBlockchainParam = normalizeNumber(
|
||||
amountSpend,
|
||||
INTERNAL_ORION_PRECISION,
|
||||
INTERNAL_PROTOCOL_PRECISION,
|
||||
BigNumber.ROUND_CEIL,
|
||||
);
|
||||
const amountReceiveBlockchainParam = normalizeNumber(
|
||||
amountReceive,
|
||||
INTERNAL_ORION_PRECISION,
|
||||
INTERNAL_PROTOCOL_PRECISION,
|
||||
BigNumber.ROUND_FLOOR,
|
||||
);
|
||||
const unsignedSwapThroughOrionPoolTx = await exchangeContract.populateTransaction.swapThroughOrionPool(
|
||||
@@ -243,7 +243,7 @@ export default async function swapMarket({
|
||||
value = amountSpendBN.minus(denormalizedAssetInExchangeBalance);
|
||||
}
|
||||
unsignedSwapThroughOrionPoolTx.value = normalizeNumber(
|
||||
value.dp(INTERNAL_ORION_PRECISION, BigNumber.ROUND_CEIL),
|
||||
value.dp(INTERNAL_PROTOCOL_PRECISION, BigNumber.ROUND_CEIL),
|
||||
NATIVE_CURRENCY_PRECISION,
|
||||
BigNumber.ROUND_CEIL,
|
||||
);
|
||||
@@ -259,7 +259,7 @@ export default async function swapMarket({
|
||||
address: ethers.constants.AddressZero,
|
||||
},
|
||||
amount: denormalizedTransactionCost.toString(),
|
||||
sources: getAvailableSources('network_fee', ethers.constants.AddressZero, 'orion_pool'),
|
||||
sources: getAvailableSources('network_fee', ethers.constants.AddressZero, 'pool'),
|
||||
});
|
||||
|
||||
// if (value.gt(0)) {
|
||||
@@ -270,7 +270,7 @@ export default async function swapMarket({
|
||||
// address: ethers.constants.AddressZero,
|
||||
// },
|
||||
// amount: value.toString(),
|
||||
// sources: getAvailableSources('amount', ethers.constants.AddressZero, 'orion_pool'),
|
||||
// sources: getAvailableSources('amount', ethers.constants.AddressZero, 'pool'),
|
||||
// });
|
||||
// }
|
||||
|
||||
@@ -285,7 +285,7 @@ export default async function swapMarket({
|
||||
return {
|
||||
amountOut: swapInfo.amountOut,
|
||||
wait: swapThroughOrionPoolTxResponse.wait,
|
||||
through: 'orion_pool',
|
||||
through: 'pool',
|
||||
txHash: swapThroughOrionPoolTxResponse.hash,
|
||||
};
|
||||
}
|
||||
@@ -339,7 +339,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 } = calculateFeeInFeeAsset(
|
||||
const { serviceFeeInFeeAsset, networkFeeInFeeAsset, totalFeeInFeeAsset } = calculateFeeInFeeAsset(
|
||||
swapInfo.orderInfo.amount,
|
||||
feeAssetPriceInOrn,
|
||||
baseAssetPriceInOrn,
|
||||
@@ -367,14 +367,14 @@ export default async function swapMarket({
|
||||
});
|
||||
|
||||
balanceGuard.registerRequirement({
|
||||
reason: 'Orion fee',
|
||||
reason: 'Service fee',
|
||||
asset: {
|
||||
name: feeAsset,
|
||||
address: feeAssetAddress,
|
||||
},
|
||||
amount: orionFeeInFeeAsset,
|
||||
amount: serviceFeeInFeeAsset,
|
||||
spenderAddress: exchangeContractAddress,
|
||||
sources: getAvailableSources('orion_fee', feeAssetAddress, 'aggregator'),
|
||||
sources: getAvailableSources('service_fee', feeAssetAddress, 'aggregator'),
|
||||
});
|
||||
|
||||
await balanceGuard.check(options?.autoApprove);
|
||||
@@ -396,7 +396,7 @@ export default async function swapMarket({
|
||||
const orderIsOk = await exchangeContract.validateOrder(signedOrder);
|
||||
if (!orderIsOk) throw new Error('Order is not valid');
|
||||
|
||||
const { orderId } = await simpleFetch(orionAggregator.placeOrder)(signedOrder, false);
|
||||
const { orderId } = await simpleFetch(aggregator.placeOrder)(signedOrder, false);
|
||||
options?.logger?.(`Order placed. Order id: ${orderId}`);
|
||||
|
||||
return {
|
||||
@@ -406,7 +406,7 @@ export default async function swapMarket({
|
||||
reject(new Error('Timeout'))
|
||||
}, 60000);
|
||||
const interval = setInterval(() => {
|
||||
simpleFetch(orionAggregator.getOrder)(orderId).then((data) => {
|
||||
simpleFetch(aggregator.getOrder)(orderId).then((data) => {
|
||||
if (data.order.status === 'SETTLED') {
|
||||
options?.logger?.(`Order ${orderId} settled`);
|
||||
clearTimeout(timeout);
|
||||
@@ -3,9 +3,9 @@ import { ethers } from 'ethers';
|
||||
import { Exchange__factory } from '@orionprotocol/contracts/lib/ethers-v5/index.js';
|
||||
import getBalances from '../../utils/getBalances.js';
|
||||
import BalanceGuard from '../../BalanceGuard.js';
|
||||
import type OrionUnit from '../index.js';
|
||||
import type Unit from '../index.js';
|
||||
import {
|
||||
INTERNAL_ORION_PRECISION, NATIVE_CURRENCY_PRECISION, WITHDRAW_GAS_LIMIT,
|
||||
INTERNAL_PROTOCOL_PRECISION, NATIVE_CURRENCY_PRECISION, WITHDRAW_GAS_LIMIT,
|
||||
} from '../../constants/index.js';
|
||||
import { denormalizeNumber, normalizeNumber } from '../../utils/index.js';
|
||||
import getNativeCryptocurrencyName from '../../utils/getNativeCryptocurrencyName.js';
|
||||
@@ -15,14 +15,14 @@ export type WithdrawParams = {
|
||||
asset: string
|
||||
amount: BigNumber.Value
|
||||
signer: ethers.Signer
|
||||
orionUnit: OrionUnit
|
||||
unit: Unit
|
||||
}
|
||||
|
||||
export default async function withdraw({
|
||||
asset,
|
||||
amount,
|
||||
signer,
|
||||
orionUnit,
|
||||
unit,
|
||||
}: WithdrawParams) {
|
||||
if (asset === '') throw new Error('Asset can not be empty');
|
||||
|
||||
@@ -33,16 +33,16 @@ export default async function withdraw({
|
||||
const walletAddress = await signer.getAddress();
|
||||
|
||||
const {
|
||||
orionBlockchain, orionAggregator, provider, chainId,
|
||||
} = orionUnit;
|
||||
blockchainService, aggregator, provider, chainId,
|
||||
} = unit;
|
||||
const {
|
||||
exchangeContractAddress,
|
||||
assetToAddress,
|
||||
} = await simpleFetch(orionBlockchain.getInfo)();
|
||||
} = await simpleFetch(blockchainService.getInfo)();
|
||||
|
||||
const nativeCryptocurrency = getNativeCryptocurrencyName(assetToAddress);
|
||||
const exchangeContract = Exchange__factory.connect(exchangeContractAddress, provider);
|
||||
const gasPriceWei = await simpleFetch(orionBlockchain.getGasPriceWei)();
|
||||
const gasPriceWei = await simpleFetch(blockchainService.getGasPriceWei)();
|
||||
|
||||
const assetAddress = assetToAddress[asset];
|
||||
if (assetAddress === undefined) throw new Error(`Asset '${asset}' not found`);
|
||||
@@ -52,7 +52,7 @@ export default async function withdraw({
|
||||
[asset]: assetAddress,
|
||||
[nativeCryptocurrency]: ethers.constants.AddressZero,
|
||||
},
|
||||
orionAggregator,
|
||||
aggregator,
|
||||
walletAddress,
|
||||
exchangeContract,
|
||||
provider,
|
||||
@@ -80,7 +80,7 @@ export default async function withdraw({
|
||||
|
||||
const unsignedTx = await exchangeContract.populateTransaction.withdraw(
|
||||
assetAddress,
|
||||
normalizeNumber(amount, INTERNAL_ORION_PRECISION, BigNumber.ROUND_FLOOR),
|
||||
normalizeNumber(amount, INTERNAL_PROTOCOL_PRECISION, BigNumber.ROUND_FLOOR),
|
||||
);
|
||||
unsignedTx.gasLimit = ethers.BigNumber.from(WITHDRAW_GAS_LIMIT);
|
||||
|
||||
@@ -2,9 +2,9 @@ import { Exchange__factory, IUniswapV2Pair__factory, IUniswapV2Router__factory }
|
||||
import { BigNumber } from 'bignumber.js';
|
||||
import { ethers } from 'ethers';
|
||||
import { simpleFetch } from 'simple-typed-fetch';
|
||||
import type OrionUnit from '../index.js';
|
||||
import type Unit from '../index.js';
|
||||
import BalanceGuard from '../../BalanceGuard.js';
|
||||
import { ADD_LIQUIDITY_GAS_LIMIT, INTERNAL_ORION_PRECISION, NATIVE_CURRENCY_PRECISION } from '../../constants/index.js';
|
||||
import { ADD_LIQUIDITY_GAS_LIMIT, INTERNAL_PROTOCOL_PRECISION, NATIVE_CURRENCY_PRECISION } from '../../constants/index.js';
|
||||
import { denormalizeNumber, normalizeNumber } from '../../utils/index.js';
|
||||
import getBalances from '../../utils/getBalances.js';
|
||||
import getNativeCryptocurrencyName from '../../utils/getNativeCryptocurrencyName.js';
|
||||
@@ -24,10 +24,10 @@ export type RemoveAllLiquidityParams = {
|
||||
}
|
||||
|
||||
export default class FarmingManager {
|
||||
private readonly orionUnit: OrionUnit;
|
||||
private readonly unit: Unit;
|
||||
|
||||
constructor(orionUnit: OrionUnit) {
|
||||
this.orionUnit = orionUnit;
|
||||
constructor(unit: Unit) {
|
||||
this.unit = unit;
|
||||
}
|
||||
|
||||
public async addLiquidity({
|
||||
@@ -49,12 +49,12 @@ export default class FarmingManager {
|
||||
exchangeContractAddress,
|
||||
assetToAddress,
|
||||
assetToDecimals,
|
||||
} = await simpleFetch(this.orionUnit.orionBlockchain.getInfo)();
|
||||
} = await simpleFetch(this.unit.blockchainService.getInfo)();
|
||||
|
||||
const walletAddress = await signer.getAddress();
|
||||
|
||||
const exchangeContract = Exchange__factory
|
||||
.connect(exchangeContractAddress, this.orionUnit.provider);
|
||||
.connect(exchangeContractAddress, this.unit.provider);
|
||||
|
||||
const assetAAddress = assetToAddress[assetA];
|
||||
if (assetAAddress === undefined) throw new Error(`Asset '${assetA}' not found`);
|
||||
@@ -73,10 +73,10 @@ export default class FarmingManager {
|
||||
[assetB]: assetBAddress,
|
||||
[nativeCryptocurrency]: ethers.constants.AddressZero,
|
||||
},
|
||||
this.orionUnit.orionAggregator,
|
||||
this.unit.aggregator,
|
||||
walletAddress,
|
||||
exchangeContract,
|
||||
this.orionUnit.provider,
|
||||
this.unit.provider,
|
||||
);
|
||||
const balanceGuard = new BalanceGuard(
|
||||
balances,
|
||||
@@ -84,18 +84,18 @@ export default class FarmingManager {
|
||||
address: ethers.constants.AddressZero,
|
||||
name: nativeCryptocurrency,
|
||||
},
|
||||
this.orionUnit.provider,
|
||||
this.unit.provider,
|
||||
signer,
|
||||
);
|
||||
|
||||
const poolsConfig = await simpleFetch(this.orionUnit.orionBlockchain.getPoolsConfig)();
|
||||
const poolsConfig = await simpleFetch(this.unit.blockchainService.getPoolsConfig)();
|
||||
const pool = poolsConfig.pools[poolName];
|
||||
if (!pool) throw new Error(`Pool ${poolName} not found`);
|
||||
|
||||
const pairContract = IUniswapV2Pair__factory
|
||||
.connect(pool.lpTokenAddress, this.orionUnit.provider);
|
||||
.connect(pool.lpTokenAddress, this.unit.provider);
|
||||
const routerContract = IUniswapV2Router__factory
|
||||
.connect(poolsConfig.routerAddress, this.orionUnit.provider);
|
||||
.connect(poolsConfig.routerAddress, this.unit.provider);
|
||||
|
||||
let pairTokensIsInversed = false;
|
||||
const token0 = await pairContract.token0();
|
||||
@@ -149,20 +149,20 @@ export default class FarmingManager {
|
||||
assetBIsNativeCurrency ? assetBAddress : assetAAddress,
|
||||
assetBIsNativeCurrency ? assetAAddress : assetBAddress,
|
||||
assetBIsNativeCurrency
|
||||
? normalizeNumber(assetBAmount, INTERNAL_ORION_PRECISION, BigNumber.ROUND_FLOOR)
|
||||
: normalizeNumber(assetAAmount, INTERNAL_ORION_PRECISION, BigNumber.ROUND_FLOOR),
|
||||
? normalizeNumber(assetBAmount, INTERNAL_PROTOCOL_PRECISION, BigNumber.ROUND_FLOOR)
|
||||
: normalizeNumber(assetAAmount, INTERNAL_PROTOCOL_PRECISION, BigNumber.ROUND_FLOOR),
|
||||
assetBIsNativeCurrency
|
||||
? normalizeNumber(assetAAmount, INTERNAL_ORION_PRECISION, BigNumber.ROUND_FLOOR)
|
||||
: normalizeNumber(assetBAmount, INTERNAL_ORION_PRECISION, BigNumber.ROUND_FLOOR),
|
||||
? normalizeNumber(assetAAmount, INTERNAL_PROTOCOL_PRECISION, BigNumber.ROUND_FLOOR)
|
||||
: normalizeNumber(assetBAmount, INTERNAL_PROTOCOL_PRECISION, BigNumber.ROUND_FLOOR),
|
||||
assetBIsNativeCurrency
|
||||
? normalizeNumber(assetBAmountWithSlippage, INTERNAL_ORION_PRECISION, BigNumber.ROUND_FLOOR)
|
||||
: normalizeNumber(assetAAmountWithSlippage, INTERNAL_ORION_PRECISION, BigNumber.ROUND_FLOOR),
|
||||
? normalizeNumber(assetBAmountWithSlippage, INTERNAL_PROTOCOL_PRECISION, BigNumber.ROUND_FLOOR)
|
||||
: normalizeNumber(assetAAmountWithSlippage, INTERNAL_PROTOCOL_PRECISION, BigNumber.ROUND_FLOOR),
|
||||
assetBIsNativeCurrency
|
||||
? normalizeNumber(assetAAmountWithSlippage, INTERNAL_ORION_PRECISION, BigNumber.ROUND_FLOOR)
|
||||
: normalizeNumber(assetBAmountWithSlippage, INTERNAL_ORION_PRECISION, BigNumber.ROUND_FLOOR),
|
||||
? normalizeNumber(assetAAmountWithSlippage, INTERNAL_PROTOCOL_PRECISION, BigNumber.ROUND_FLOOR)
|
||||
: normalizeNumber(assetBAmountWithSlippage, INTERNAL_PROTOCOL_PRECISION, BigNumber.ROUND_FLOOR),
|
||||
);
|
||||
|
||||
const gasPrice = await this.orionUnit.provider.getGasPrice();
|
||||
const gasPrice = await this.unit.provider.getGasPrice();
|
||||
|
||||
const transactionCost = ethers.BigNumber.from(ADD_LIQUIDITY_GAS_LIMIT).mul(gasPrice);
|
||||
const denormalizedTransactionCost = denormalizeNumber(transactionCost, NATIVE_CURRENCY_PRECISION);
|
||||
@@ -177,9 +177,9 @@ export default class FarmingManager {
|
||||
sources: ['wallet'],
|
||||
});
|
||||
|
||||
const nonce = await this.orionUnit.provider.getTransactionCount(walletAddress, 'pending');
|
||||
const nonce = await this.unit.provider.getTransactionCount(walletAddress, 'pending');
|
||||
|
||||
const network = await this.orionUnit.provider.getNetwork();
|
||||
const network = await this.unit.provider.getNetwork();
|
||||
|
||||
if (assetAIsNativeCurrency || assetBIsNativeCurrency) {
|
||||
const contractBalance = balances[nativeCryptocurrency]?.exchange;
|
||||
@@ -199,13 +199,13 @@ export default class FarmingManager {
|
||||
unsignedTx.gasPrice = gasPrice;
|
||||
unsignedTx.nonce = nonce;
|
||||
unsignedTx.from = walletAddress;
|
||||
const gasLimit = await this.orionUnit.provider.estimateGas(unsignedTx);
|
||||
const gasLimit = await this.unit.provider.estimateGas(unsignedTx);
|
||||
unsignedTx.gasLimit = gasLimit;
|
||||
|
||||
await balanceGuard.check(true);
|
||||
|
||||
const signedTx = await signer.signTransaction(unsignedTx);
|
||||
const txResponse = await this.orionUnit.provider.sendTransaction(signedTx);
|
||||
const txResponse = await this.unit.provider.sendTransaction(signedTx);
|
||||
console.log(`Add liquidity tx sent: ${txResponse.hash}. Waiting for confirmation...`);
|
||||
const txReceipt = await txResponse.wait();
|
||||
if (txReceipt.status === 1) {
|
||||
@@ -228,7 +228,7 @@ export default class FarmingManager {
|
||||
assetToAddress,
|
||||
assetToDecimals,
|
||||
exchangeContractAddress,
|
||||
} = await simpleFetch(this.orionUnit.orionBlockchain.getInfo)();
|
||||
} = await simpleFetch(this.unit.blockchainService.getInfo)();
|
||||
|
||||
const assetAAddress = assetToAddress[assetA];
|
||||
if (assetAAddress === undefined) throw new Error(`Asset '${assetA}' not found`);
|
||||
@@ -240,14 +240,14 @@ export default class FarmingManager {
|
||||
const assetBDecimals = assetToDecimals[assetB];
|
||||
if (assetBDecimals === undefined) throw new Error(`Decimals for asset '${assetB}' not found`);
|
||||
|
||||
const poolsConfig = await simpleFetch(this.orionUnit.orionBlockchain.getPoolsConfig)();
|
||||
const poolsConfig = await simpleFetch(this.unit.blockchainService.getPoolsConfig)();
|
||||
const pool = poolsConfig.pools[poolName];
|
||||
if (!pool) throw new Error(`Pool ${poolName} not found`);
|
||||
|
||||
const walletAddress = await signer.getAddress();
|
||||
|
||||
const exchangeContract = Exchange__factory
|
||||
.connect(exchangeContractAddress, this.orionUnit.provider);
|
||||
.connect(exchangeContractAddress, this.unit.provider);
|
||||
const nativeCryptocurrency = getNativeCryptocurrencyName(assetToAddress);
|
||||
const balances = await getBalances(
|
||||
{
|
||||
@@ -256,10 +256,10 @@ export default class FarmingManager {
|
||||
[`${poolName} LP Token`]: pool.lpTokenAddress,
|
||||
[nativeCryptocurrency]: ethers.constants.AddressZero,
|
||||
},
|
||||
this.orionUnit.orionAggregator,
|
||||
this.unit.aggregator,
|
||||
walletAddress,
|
||||
exchangeContract,
|
||||
this.orionUnit.provider,
|
||||
this.unit.provider,
|
||||
);
|
||||
|
||||
const balanceGuard = new BalanceGuard(
|
||||
@@ -268,17 +268,17 @@ export default class FarmingManager {
|
||||
address: ethers.constants.AddressZero,
|
||||
name: nativeCryptocurrency,
|
||||
},
|
||||
this.orionUnit.provider,
|
||||
this.unit.provider,
|
||||
signer,
|
||||
);
|
||||
|
||||
const pairContract = IUniswapV2Pair__factory
|
||||
.connect(pool.lpTokenAddress, this.orionUnit.provider);
|
||||
.connect(pool.lpTokenAddress, this.unit.provider);
|
||||
|
||||
const { _reserve0, _reserve1 } = await pairContract.getReserves();
|
||||
|
||||
const routerContract = IUniswapV2Router__factory
|
||||
.connect(poolsConfig.routerAddress, this.orionUnit.provider);
|
||||
.connect(poolsConfig.routerAddress, this.unit.provider);
|
||||
|
||||
let pairTokensIsInversed = false;
|
||||
|
||||
@@ -371,7 +371,7 @@ export default class FarmingManager {
|
||||
);
|
||||
}
|
||||
|
||||
const gasPrice = await this.orionUnit.provider.getGasPrice();
|
||||
const gasPrice = await this.unit.provider.getGasPrice();
|
||||
|
||||
const transactionCost = ethers.BigNumber.from(ADD_LIQUIDITY_GAS_LIMIT).mul(gasPrice);
|
||||
const denormalizedTransactionCost = denormalizeNumber(transactionCost, NATIVE_CURRENCY_PRECISION);
|
||||
@@ -387,18 +387,18 @@ export default class FarmingManager {
|
||||
});
|
||||
|
||||
await balanceGuard.check(true);
|
||||
const nonce = await this.orionUnit.provider.getTransactionCount(walletAddress, 'pending');
|
||||
const network = await this.orionUnit.provider.getNetwork();
|
||||
const nonce = await this.unit.provider.getTransactionCount(walletAddress, 'pending');
|
||||
const network = await this.unit.provider.getNetwork();
|
||||
|
||||
unsignedTx.chainId = network.chainId;
|
||||
unsignedTx.gasPrice = gasPrice;
|
||||
unsignedTx.nonce = nonce;
|
||||
unsignedTx.from = walletAddress;
|
||||
const gasLimit = await this.orionUnit.provider.estimateGas(unsignedTx);
|
||||
const gasLimit = await this.unit.provider.estimateGas(unsignedTx);
|
||||
unsignedTx.gasLimit = gasLimit;
|
||||
|
||||
const signedTx = await signer.signTransaction(unsignedTx);
|
||||
const txResponse = await this.orionUnit.provider.sendTransaction(signedTx);
|
||||
const txResponse = await this.unit.provider.sendTransaction(signedTx);
|
||||
console.log(`Remove all liquidity tx sent: ${txResponse.hash}. Waiting for confirmation...`);
|
||||
const txReceipt = await txResponse.wait();
|
||||
if (txReceipt.status === 1) {
|
||||
@@ -1,8 +1,8 @@
|
||||
import { ethers } from 'ethers';
|
||||
import { OrionAggregator } from '../services/OrionAggregator/index.js';
|
||||
import { OrionBlockchain } from '../services/OrionBlockchain/index.js';
|
||||
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, VerboseOrionUnitConfig } 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';
|
||||
@@ -13,20 +13,16 @@ type KnownConfig = {
|
||||
chainId: SupportedChainId
|
||||
}
|
||||
|
||||
// type OrionUnitConfig = KnownConfig | VerboseOrionUnitConfig;
|
||||
|
||||
export default class OrionUnit {
|
||||
// public readonly env?: string;
|
||||
|
||||
export default class Unit {
|
||||
public readonly networkCode: typeof networkCodes[number];
|
||||
|
||||
public readonly chainId: SupportedChainId;
|
||||
|
||||
public readonly provider: ethers.providers.StaticJsonRpcProvider;
|
||||
|
||||
public readonly orionBlockchain: OrionBlockchain;
|
||||
public readonly blockchainService: BlockchainService;
|
||||
|
||||
public readonly orionAggregator: OrionAggregator;
|
||||
public readonly aggregator: Aggregator;
|
||||
|
||||
public readonly priceFeed: PriceFeed;
|
||||
|
||||
@@ -34,12 +30,9 @@ export default class OrionUnit {
|
||||
|
||||
public readonly farmingManager: FarmingManager;
|
||||
|
||||
public readonly config: VerboseOrionUnitConfig;
|
||||
public readonly config: VerboseUnitConfig;
|
||||
|
||||
// constructor(config: KnownConfig);
|
||||
// constructor(config: VerboseConfig);
|
||||
|
||||
constructor(config: KnownConfig | VerboseOrionUnitConfig) {
|
||||
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(', ')}`);
|
||||
@@ -54,10 +47,10 @@ export default class OrionUnit {
|
||||
chainId: config.chainId,
|
||||
nodeJsonRpc: networkConfig.rpc ?? chainConfig.rpc,
|
||||
services: {
|
||||
orionBlockchain: {
|
||||
blockchainService: {
|
||||
http: networkConfig.api + networkConfig.services.blockchain.http,
|
||||
},
|
||||
orionAggregator: {
|
||||
aggregator: {
|
||||
http: networkConfig.api + networkConfig.services.aggregator.http,
|
||||
ws: networkConfig.api + networkConfig.services.aggregator.ws,
|
||||
},
|
||||
@@ -72,8 +65,6 @@ export default class OrionUnit {
|
||||
const chainInfo = chains[config.chainId];
|
||||
if (!chainInfo) throw new Error('Chain info is required');
|
||||
|
||||
// if ('env' in config)
|
||||
// this.env = config.env;
|
||||
this.chainId = config.chainId;
|
||||
this.networkCode = chainInfo.code;
|
||||
const intNetwork = parseInt(this.chainId, 10);
|
||||
@@ -81,52 +72,13 @@ export default class OrionUnit {
|
||||
this.provider = new ethers.providers.StaticJsonRpcProvider(this.config.nodeJsonRpc, intNetwork);
|
||||
this.provider.pollingInterval = 1000;
|
||||
|
||||
this.orionBlockchain = new OrionBlockchain(this.config.services.orionBlockchain.http);
|
||||
this.orionAggregator = new OrionAggregator(
|
||||
this.config.services.orionAggregator.http,
|
||||
this.config.services.orionAggregator.ws,
|
||||
this.blockchainService = new BlockchainService(this.config.services.blockchainService.http);
|
||||
this.aggregator = new Aggregator(
|
||||
this.config.services.aggregator.http,
|
||||
this.config.services.aggregator.ws,
|
||||
);
|
||||
this.priceFeed = new PriceFeed(this.config.services.priceFeed.api);
|
||||
this.exchange = new Exchange(this);
|
||||
this.farmingManager = new FarmingManager(this);
|
||||
}
|
||||
|
||||
// get siblings() {
|
||||
// if (!this.env) throw new Error('Sibling is not available, because env is not set');
|
||||
|
||||
// const envInfo = envs[this.env];
|
||||
// const envNetworks = envInfo?.networks;
|
||||
|
||||
// if (envNetworks === undefined) throw new Error('Env networks is undefined (siblings)');
|
||||
|
||||
// const orionUnits: OrionUnit[] = [];
|
||||
// Object
|
||||
// .entries(envNetworks)
|
||||
// .forEach(([chainId, config]) => {
|
||||
// if (!isValidChainId(chainId)) throw new Error('Invalid chainId');
|
||||
// if (chainId !== this.chainId) {
|
||||
// const chainConfig = chains[chainId];
|
||||
// if (!chainConfig) throw new Error('Chain config is required');
|
||||
// const orionUnit = new OrionUnit({
|
||||
// api: config.api,
|
||||
// chainId,
|
||||
// nodeJsonRpc: chainConfig.rpc ?? config.rpc,
|
||||
// services: {
|
||||
// orionBlockchain: {
|
||||
// http: config.api + config.services.blockchain.http,
|
||||
// },
|
||||
// orionAggregator: {
|
||||
// http: config.api + config.services.aggregator.http,
|
||||
// ws: config.api + config.services.aggregator.ws,
|
||||
// },
|
||||
// priceFeed: {
|
||||
// api: config.api + config.services.priceFeed.all,
|
||||
// },
|
||||
// },
|
||||
// });
|
||||
// orionUnits.push(orionUnit);
|
||||
// }
|
||||
// });
|
||||
// return orionUnits;
|
||||
// }
|
||||
}
|
||||
@@ -82,29 +82,29 @@ describe('Orion', () => {
|
||||
expect(orion.referralSystem).toBeInstanceOf(ReferralSystem);
|
||||
expect(orion.unitsArray.length).toBe(4); // eth, bsc, polygon, fantom
|
||||
|
||||
const orionUnitBSC = orion.units[SupportedChainId.BSC_TESTNET];
|
||||
expect(orionUnitBSC?.chainId).toBe(SupportedChainId.BSC_TESTNET);
|
||||
// expect(orionUnitBSC?.env).toBe('testing');
|
||||
const unitBSC = orion.units[SupportedChainId.BSC_TESTNET];
|
||||
expect(unitBSC?.chainId).toBe(SupportedChainId.BSC_TESTNET);
|
||||
// expect(unitBSC?.env).toBe('testing');
|
||||
expect(orion.getSiblingsOf(SupportedChainId.BSC_TESTNET)).toHaveLength(3);
|
||||
expect(orionUnitBSC?.networkCode).toBe('bsc');
|
||||
expect(unitBSC?.networkCode).toBe('bsc');
|
||||
|
||||
const orionUnitRopsten = orion.units[SupportedChainId.ROPSTEN]
|
||||
expect(orionUnitRopsten?.chainId).toBe(SupportedChainId.ROPSTEN);
|
||||
// expect(orionUnitRopsten?.env).toBe('testing');
|
||||
const unitRopsten = orion.units[SupportedChainId.ROPSTEN]
|
||||
expect(unitRopsten?.chainId).toBe(SupportedChainId.ROPSTEN);
|
||||
// expect(unitRopsten?.env).toBe('testing');
|
||||
expect(orion.getSiblingsOf(SupportedChainId.ROPSTEN)).toHaveLength(3);
|
||||
expect(orionUnitRopsten?.networkCode).toBe('eth');
|
||||
expect(unitRopsten?.networkCode).toBe('eth');
|
||||
|
||||
const orionUnitPolygon = orion.units[SupportedChainId.POLYGON_TESTNET];
|
||||
expect(orionUnitPolygon?.chainId).toBe(SupportedChainId.POLYGON_TESTNET);
|
||||
// expect(orionUnitPolygon?.env).toBe('testing');
|
||||
const unitPolygon = orion.units[SupportedChainId.POLYGON_TESTNET];
|
||||
expect(unitPolygon?.chainId).toBe(SupportedChainId.POLYGON_TESTNET);
|
||||
// expect(unitPolygon?.env).toBe('testing');
|
||||
expect(orion.getSiblingsOf(SupportedChainId.POLYGON_TESTNET)).toHaveLength(3);
|
||||
expect(orionUnitPolygon?.networkCode).toBe('polygon');
|
||||
expect(unitPolygon?.networkCode).toBe('polygon');
|
||||
|
||||
const orionUnitFantom = orion.units[SupportedChainId.FANTOM_TESTNET];
|
||||
expect(orionUnitFantom?.chainId).toBe(SupportedChainId.FANTOM_TESTNET);
|
||||
// expect(orionUnitFantom?.env).toBe('testing');
|
||||
const unitFantom = orion.units[SupportedChainId.FANTOM_TESTNET];
|
||||
expect(unitFantom?.chainId).toBe(SupportedChainId.FANTOM_TESTNET);
|
||||
// expect(unitFantom?.env).toBe('testing');
|
||||
expect(orion.getSiblingsOf(SupportedChainId.FANTOM_TESTNET)).toHaveLength(3);
|
||||
expect(orionUnitFantom?.networkCode).toBe('ftm');
|
||||
expect(unitFantom?.networkCode).toBe('ftm');
|
||||
});
|
||||
|
||||
test('Init Orion production', () => {
|
||||
@@ -113,35 +113,35 @@ describe('Orion', () => {
|
||||
expect(orion.referralSystem).toBeInstanceOf(ReferralSystem);
|
||||
expect(orion.unitsArray.length).toBe(5); // eth, bsc, polygon, fantom, okc
|
||||
|
||||
const orionUnitBSC = orion.units[SupportedChainId.BSC];
|
||||
expect(orionUnitBSC?.chainId).toBe(SupportedChainId.BSC);
|
||||
// expect(orionUnitBSC?.env).toBe('production');
|
||||
const unitBSC = orion.units[SupportedChainId.BSC];
|
||||
expect(unitBSC?.chainId).toBe(SupportedChainId.BSC);
|
||||
// expect(unitBSC?.env).toBe('production');
|
||||
expect(orion.getSiblingsOf(SupportedChainId.BSC)).toHaveLength(4);
|
||||
expect(orionUnitBSC?.networkCode).toBe('bsc');
|
||||
expect(unitBSC?.networkCode).toBe('bsc');
|
||||
|
||||
const orionUnitETH = orion.units[SupportedChainId.MAINNET]
|
||||
expect(orionUnitETH?.chainId).toBe(SupportedChainId.MAINNET);
|
||||
// expect(orionUnitETH?.env).toBe('production');
|
||||
const unitETH = orion.units[SupportedChainId.MAINNET]
|
||||
expect(unitETH?.chainId).toBe(SupportedChainId.MAINNET);
|
||||
// expect(unitETH?.env).toBe('production');
|
||||
expect(orion.getSiblingsOf(SupportedChainId.MAINNET)).toHaveLength(4);
|
||||
expect(orionUnitETH?.networkCode).toBe('eth');
|
||||
expect(unitETH?.networkCode).toBe('eth');
|
||||
|
||||
const orionUnitPolygon = orion.units[SupportedChainId.POLYGON];
|
||||
expect(orionUnitPolygon?.chainId).toBe(SupportedChainId.POLYGON);
|
||||
// expect(orionUnitPolygon?.env).toBe('production');
|
||||
const unitPolygon = orion.units[SupportedChainId.POLYGON];
|
||||
expect(unitPolygon?.chainId).toBe(SupportedChainId.POLYGON);
|
||||
// expect(unitPolygon?.env).toBe('production');
|
||||
expect(orion.getSiblingsOf(SupportedChainId.POLYGON)).toHaveLength(4);
|
||||
expect(orionUnitPolygon?.networkCode).toBe('polygon');
|
||||
expect(unitPolygon?.networkCode).toBe('polygon');
|
||||
|
||||
const orionUnitFantom = orion.units[SupportedChainId.FANTOM_OPERA];
|
||||
expect(orionUnitFantom?.chainId).toBe(SupportedChainId.FANTOM_OPERA);
|
||||
// expect(orionUnitFantom?.env).toBe('production');
|
||||
const unitFantom = orion.units[SupportedChainId.FANTOM_OPERA];
|
||||
expect(unitFantom?.chainId).toBe(SupportedChainId.FANTOM_OPERA);
|
||||
// expect(unitFantom?.env).toBe('production');
|
||||
expect(orion.getSiblingsOf(SupportedChainId.FANTOM_OPERA)).toHaveLength(4);
|
||||
expect(orionUnitFantom?.networkCode).toBe('ftm');
|
||||
expect(unitFantom?.networkCode).toBe('ftm');
|
||||
|
||||
const orionUnitOKC = orion.units[SupportedChainId.OKC];
|
||||
expect(orionUnitOKC?.chainId).toBe(SupportedChainId.OKC);
|
||||
// expect(orionUnitOKC?.env).toBe('production');
|
||||
const unitOKC = orion.units[SupportedChainId.OKC];
|
||||
expect(unitOKC?.chainId).toBe(SupportedChainId.OKC);
|
||||
// expect(unitOKC?.env).toBe('production');
|
||||
expect(orion.getSiblingsOf(SupportedChainId.OKC)).toHaveLength(4);
|
||||
expect(orionUnitOKC?.networkCode).toBe('okc');
|
||||
expect(unitOKC?.networkCode).toBe('okc');
|
||||
});
|
||||
|
||||
test('Init Orion custom', async () => {
|
||||
@@ -153,8 +153,8 @@ describe('Orion', () => {
|
||||
throw new Error('Server port is undefined');
|
||||
}
|
||||
|
||||
const orionBlockchainAPI = `http://localhost:${server0.port}`;
|
||||
const orionAggregatorAPI = `http://localhost:${server1.port}`;
|
||||
const blockchainServiceAPI = `http://localhost:${server0.port}`;
|
||||
const aggregatorAPI = `http://localhost:${server1.port}`;
|
||||
const orionPriceFeedAPI = `http://localhost:${server2.port}`;
|
||||
|
||||
const orion = new Orion({
|
||||
@@ -166,11 +166,11 @@ describe('Orion', () => {
|
||||
chainId: SupportedChainId.MAINNET,
|
||||
nodeJsonRpc: 'https://cloudflare-eth.com/',
|
||||
services: {
|
||||
orionBlockchain: {
|
||||
http: orionBlockchainAPI,
|
||||
blockchainService: {
|
||||
http: blockchainServiceAPI,
|
||||
},
|
||||
orionAggregator: {
|
||||
http: orionAggregatorAPI + '/backend',
|
||||
aggregator: {
|
||||
http: aggregatorAPI + '/backend',
|
||||
ws: `http://localhost:${server1.port}/v1`,
|
||||
},
|
||||
priceFeed: {
|
||||
@@ -181,28 +181,28 @@ describe('Orion', () => {
|
||||
}
|
||||
});
|
||||
|
||||
const [orionUnit] = orion.unitsArray;
|
||||
if (!orionUnit) {
|
||||
const [unit] = orion.unitsArray;
|
||||
if (!unit) {
|
||||
throw new Error('Orion unit is not defined');
|
||||
}
|
||||
expect(orion.referralSystem).toBeInstanceOf(ReferralSystem);
|
||||
expect(orion.unitsArray.length).toBe(1); // eth
|
||||
expect(orion.referralSystem.api).toBe('https://referral-api.orionprotocol.io');
|
||||
expect(orionUnit.chainId).toBe(SupportedChainId.MAINNET);
|
||||
// expect(orionUnit.env).toBeUndefined();
|
||||
// expect(orion.units[0]?.orionAggregator.api).toBe('http://localhost:3001');
|
||||
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');
|
||||
expect(orionUnit.provider.connection.url).toBe('https://cloudflare-eth.com/');
|
||||
expect(unit.chainId).toBe(SupportedChainId.MAINNET);
|
||||
// expect(unit.env).toBeUndefined();
|
||||
// expect(orion.units[0]?.aggregator.api).toBe('http://localhost:3001');
|
||||
expect(unit.aggregator.ws.api).toBe(`ws://localhost:${server1.port}/v1`);
|
||||
expect(unit.blockchainService.api).toBe(blockchainServiceAPI);
|
||||
expect(unit.priceFeed.api).toBe(orionPriceFeedAPI + '/price-feed');
|
||||
expect(unit.provider.connection.url).toBe('https://cloudflare-eth.com/');
|
||||
|
||||
const info = await simpleFetch(orionUnit.orionBlockchain.getInfo)();
|
||||
const info = await simpleFetch(unit.blockchainService.getInfo)();
|
||||
expect(info).toBeDefined();
|
||||
|
||||
const spotData = await simpleFetch(orionUnit.orionAggregator.getPairConfigs)('spot');
|
||||
const spotData = await simpleFetch(unit.aggregator.getPairConfigs)('spot');
|
||||
expect(spotData).toBeDefined();
|
||||
|
||||
const priceData = await simpleFetch(orionUnit.priceFeed.getCandles)(
|
||||
const priceData = await simpleFetch(unit.priceFeed.getCandles)(
|
||||
'BTC-USDT',
|
||||
Math.floor((Date.now() - 1000 * 60 * 60 * 24 * 30) / 1000), // 1 month ago
|
||||
Math.floor(Date.now() / 1000), // now
|
||||
@@ -211,7 +211,7 @@ describe('Orion', () => {
|
||||
expect(priceData).toBeDefined();
|
||||
|
||||
const allTickersDone = await new Promise<boolean>((resolve, reject) => {
|
||||
const { unsubscribe } = orionUnit.priceFeed.ws.subscribe(
|
||||
const { unsubscribe } = unit.priceFeed.ws.subscribe(
|
||||
'allTickers',
|
||||
{
|
||||
callback: () => {
|
||||
@@ -223,7 +223,7 @@ describe('Orion', () => {
|
||||
)
|
||||
const timeout = setTimeout(() => {
|
||||
unsubscribe();
|
||||
reject(new Error(`Timeout: ${orionUnit.priceFeed.wsUrl}`));
|
||||
reject(new Error(`Timeout: ${unit.priceFeed.wsUrl}`));
|
||||
}, 10000);
|
||||
});
|
||||
expect(allTickersDone).toBe(true);
|
||||
@@ -244,24 +244,24 @@ describe('Orion', () => {
|
||||
}
|
||||
});
|
||||
|
||||
const bscOrionUnit = orion.units[SupportedChainId.BSC_TESTNET]
|
||||
expect(bscOrionUnit?.provider.connection.url).toBe('https://data-seed-prebsc-1-s1.binance.org:8545/');
|
||||
const bscUnit = orion.units[SupportedChainId.BSC_TESTNET]
|
||||
expect(bscUnit?.provider.connection.url).toBe('https://data-seed-prebsc-1-s1.binance.org:8545/');
|
||||
expect(orion.referralSystem.api).toBe('https://zxczxc.orionprotocol.io');
|
||||
});
|
||||
|
||||
test('Orion Responses', async () => {
|
||||
const orion = new Orion('testing');
|
||||
|
||||
const orionUnitBSC = orion.units[SupportedChainId.BSC_TESTNET]
|
||||
if (!orionUnitBSC) {
|
||||
const unitBSC = orion.units[SupportedChainId.BSC_TESTNET]
|
||||
if (!unitBSC) {
|
||||
throw new Error('Orion unit not found');
|
||||
}
|
||||
const info = await simpleFetch(orionUnitBSC.orionBlockchain.getInfo)();
|
||||
const info = await simpleFetch(unitBSC.blockchainService.getInfo)();
|
||||
expect(info).toBeDefined();
|
||||
expect(info.chainId).toBe(97);
|
||||
expect(info.chainName).toBe('bsc-testnet');
|
||||
|
||||
const pairConfigs = await simpleFetch(orionUnitBSC.orionAggregator.getPairConfigs)('spot');
|
||||
const pairConfigs = await simpleFetch(unitBSC.aggregator.getPairConfigs)('spot');
|
||||
expect(pairConfigs).toBeDefined();
|
||||
expect(pairConfigs.length).toBeGreaterThan(0);
|
||||
|
||||
@@ -270,17 +270,17 @@ describe('Orion', () => {
|
||||
reject(new Error('Timeout'));
|
||||
}, 10000);
|
||||
|
||||
orionUnitBSC.orionAggregator.ws.subscribe('aobus', {
|
||||
unitBSC.aggregator.ws.subscribe('aobus', {
|
||||
payload: 'ORN-USDT',
|
||||
callback: () => {
|
||||
resolve(true);
|
||||
orionUnitBSC.orionAggregator.ws.destroy();
|
||||
unitBSC.aggregator.ws.destroy();
|
||||
clearTimeout(timeout);
|
||||
}
|
||||
})
|
||||
});
|
||||
expect(aobusDone).toBe(true);
|
||||
const candles = await simpleFetch(orionUnitBSC.priceFeed.getCandles)(
|
||||
const candles = await simpleFetch(unitBSC.priceFeed.getCandles)(
|
||||
'BTC-USDT',
|
||||
Math.floor((Date.now() - 1000 * 60 * 60 * 24 * 30) / 1000), // 1 month ago
|
||||
Math.floor(Date.now() / 1000), // now
|
||||
@@ -293,7 +293,7 @@ describe('Orion', () => {
|
||||
reject(new Error('Timeout'));
|
||||
}, 10000);
|
||||
|
||||
const { unsubscribe } = orionUnitBSC.priceFeed.ws.subscribe(
|
||||
const { unsubscribe } = unitBSC.priceFeed.ws.subscribe(
|
||||
'allTickers',
|
||||
{
|
||||
callback: () => {
|
||||
@@ -306,9 +306,9 @@ describe('Orion', () => {
|
||||
});
|
||||
expect(allTickersDone).toBe(true);
|
||||
|
||||
const blockNumber = await orionUnitBSC.provider.getBlockNumber();
|
||||
const blockNumber = await unitBSC.provider.getBlockNumber();
|
||||
expect(blockNumber).toBeDefined();
|
||||
const network = await orionUnitBSC.provider.getNetwork();
|
||||
const network = await unitBSC.provider.getNetwork();
|
||||
expect(network.chainId).toBe(97);
|
||||
|
||||
const zeroAddressWithout0x = ethers.constants.AddressZero.slice(2);
|
||||
@@ -319,11 +319,11 @@ describe('Orion', () => {
|
||||
|
||||
test('Get Orion unit by networkCode', () => {
|
||||
const orionTesting = new Orion('testing');
|
||||
const orionUnitBSCTesting = orionTesting.getUnit('bsc');
|
||||
expect(orionUnitBSCTesting.chainId).toBe(SupportedChainId.BSC_TESTNET);
|
||||
const unitBSCTesting = orionTesting.getUnit('bsc');
|
||||
expect(unitBSCTesting.chainId).toBe(SupportedChainId.BSC_TESTNET);
|
||||
|
||||
const orionMainnet = new Orion('production');
|
||||
const orionUnitBSCMainnet = orionMainnet.getUnit('bsc');
|
||||
expect(orionUnitBSCMainnet.chainId).toBe(SupportedChainId.BSC);
|
||||
const unitBSCMainnet = orionMainnet.getUnit('bsc');
|
||||
expect(unitBSCMainnet.chainId).toBe(SupportedChainId.BSC);
|
||||
})
|
||||
});
|
||||
|
||||
@@ -9,19 +9,19 @@ describe('Orion Aggregator', () => {
|
||||
|
||||
await new Promise((resolve, reject) => {
|
||||
const timeout = setTimeout(() => {
|
||||
bscUnit.orionAggregator.ws.unsubscribe(subId);
|
||||
bscUnit.orionAggregator.ws.destroy()
|
||||
bscUnit.aggregator.ws.unsubscribe(subId);
|
||||
bscUnit.aggregator.ws.destroy()
|
||||
reject(new Error('Timeout'));
|
||||
}, 10000);
|
||||
// bscUnit.orionAggregator.ws.onError = console.error;
|
||||
// bscUnit.aggregator.ws.onError = console.error;
|
||||
const payload = 'adsv-sdfb';
|
||||
subId = bscUnit.orionAggregator.ws.subscribe('aus', {
|
||||
subId = bscUnit.aggregator.ws.subscribe('aus', {
|
||||
payload,
|
||||
callback: () => null,
|
||||
errorCb: (message) => {
|
||||
expect(message).toContain(`Address '${payload}' is not hexadecimal`);
|
||||
clearTimeout(timeout);
|
||||
bscUnit.orionAggregator.ws.destroy()
|
||||
bscUnit.aggregator.ws.destroy()
|
||||
resolve(true);
|
||||
}
|
||||
})
|
||||
@@ -36,18 +36,18 @@ describe('Orion Aggregator', () => {
|
||||
|
||||
await new Promise((resolve, reject) => {
|
||||
const timeout = setTimeout(() => {
|
||||
bscUnit.orionAggregator.ws.unsubscribe(subId);
|
||||
bscUnit.orionAggregator.ws.destroy()
|
||||
bscUnit.aggregator.ws.unsubscribe(subId);
|
||||
bscUnit.aggregator.ws.destroy()
|
||||
reject(new Error('Timeout'));
|
||||
}, 10000);
|
||||
const payload = 'BTCUSDF';
|
||||
subId = bscUnit.orionAggregator.ws.subscribe('aobus', {
|
||||
subId = bscUnit.aggregator.ws.subscribe('aobus', {
|
||||
payload,
|
||||
callback: () => null,
|
||||
errorCb: (message) => {
|
||||
console.log(message);
|
||||
clearTimeout(timeout);
|
||||
bscUnit.orionAggregator.ws.destroy()
|
||||
bscUnit.aggregator.ws.destroy()
|
||||
resolve(true);
|
||||
}
|
||||
})
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { ethers } from 'ethers';
|
||||
import Orion from '../Orion/index.js';
|
||||
import swapMarket from '../OrionUnit/Exchange/swapMarket.js';
|
||||
import swapMarket from '../Unit/Exchange/swapMarket.js';
|
||||
|
||||
const privateKey = process.env['PRIVATE_KEY']
|
||||
if (privateKey === undefined) throw new Error('Private key is required');
|
||||
@@ -23,7 +23,7 @@ describe('Spot trading', () => {
|
||||
type: 'exactSpend',
|
||||
signer: wallet,
|
||||
feeAsset: 'USDT',
|
||||
orionUnit: bscUnit,
|
||||
unit: bscUnit,
|
||||
slippagePercent: 1,
|
||||
// options: {
|
||||
// logger: console.log
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
// https://github.com/orionprotocol/orion-aggregator/blob/11a7847af958726c65ae5f7b14ee6463c75ea14b/src/main/java/io/orionprotocol/aggregator/model/Exchange.java
|
||||
export default [
|
||||
// CEXes
|
||||
'ASCENDEX',
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import subOrderStatuses from './subOrderStatuses.js';
|
||||
|
||||
// https://github.com/orionprotocol/orion-aggregator/blob/develop/src/main/java/io/orionprotocol/aggregator/model/order/status/OrderStatus.java
|
||||
const orderStatuses = [
|
||||
...subOrderStatuses,
|
||||
'ROUTING', // order got sub orders, but not all of them have status ACCEPTED
|
||||
|
||||
@@ -1,2 +1,2 @@
|
||||
export const INTERNAL_ORION_PRECISION = 8;
|
||||
export const INTERNAL_PROTOCOL_PRECISION = 8;
|
||||
export const NATIVE_CURRENCY_PRECISION = 18;
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
// https://github.com/orionprotocol/orion-aggregator/blob/develop/src/main/java/io/orionprotocol/aggregator/model/order/status/SubOrderStatus.java
|
||||
const subOrderStatuses = [
|
||||
'NEW', // created, wasn't added to IOB or wasn't accepted by the broker
|
||||
'ACCEPTED', // added to IOB or accepted by the broker
|
||||
|
||||
@@ -2,7 +2,7 @@ import type { TypedDataSigner } from '@ethersproject/abstract-signer';
|
||||
import { BigNumber } from 'bignumber.js';
|
||||
import type { ethers } from 'ethers';
|
||||
import { joinSignature, splitSignature } from 'ethers/lib/utils.js';
|
||||
import { INTERNAL_ORION_PRECISION } from '../constants/index.js';
|
||||
import { INTERNAL_PROTOCOL_PRECISION } from '../constants/index.js';
|
||||
import type { CFDOrder, SignedCFDOrder, SupportedChainId } from '../types.js';
|
||||
import normalizeNumber from '../utils/normalizeNumber.js';
|
||||
import getDomainData from './getDomainData.js';
|
||||
@@ -37,17 +37,17 @@ export const signCFDOrder = async (
|
||||
instrumentAddress,
|
||||
amount: normalizeNumber(
|
||||
amount,
|
||||
INTERNAL_ORION_PRECISION,
|
||||
INTERNAL_PROTOCOL_PRECISION,
|
||||
BigNumber.ROUND_FLOOR,
|
||||
).toNumber(),
|
||||
price: normalizeNumber(
|
||||
price,
|
||||
INTERNAL_ORION_PRECISION,
|
||||
INTERNAL_PROTOCOL_PRECISION,
|
||||
BigNumber.ROUND_FLOOR,
|
||||
).toNumber(),
|
||||
matcherFee: normalizeNumber(
|
||||
matcherFee,
|
||||
INTERNAL_ORION_PRECISION,
|
||||
INTERNAL_PROTOCOL_PRECISION,
|
||||
BigNumber.ROUND_CEIL, // ROUND_CEIL because we don't want get "not enough fee" error
|
||||
).toNumber(),
|
||||
nonce,
|
||||
|
||||
@@ -2,7 +2,7 @@ import type { TypedDataSigner } from '@ethersproject/abstract-signer';
|
||||
import { BigNumber } from 'bignumber.js';
|
||||
import type { ethers } from 'ethers';
|
||||
import { joinSignature, splitSignature } from 'ethers/lib/utils.js';
|
||||
import { INTERNAL_ORION_PRECISION } from '../constants/index.js';
|
||||
import { INTERNAL_PROTOCOL_PRECISION } from '../constants/index.js';
|
||||
import ORDER_TYPES from '../constants/orderTypes.js';
|
||||
import type { Order, SignedOrder, SupportedChainId } from '../types.js';
|
||||
import normalizeNumber from '../utils/normalizeNumber.js';
|
||||
@@ -23,7 +23,7 @@ export const signOrder = async (
|
||||
matcherFee: BigNumber.Value,
|
||||
senderAddress: string,
|
||||
matcherAddress: string,
|
||||
orionFeeAssetAddr: string,
|
||||
serviceFeeAssetAddr: string,
|
||||
usePersonalSign: boolean,
|
||||
signer: ethers.Signer,
|
||||
chainId: SupportedChainId,
|
||||
@@ -36,20 +36,20 @@ export const signOrder = async (
|
||||
matcherAddress,
|
||||
baseAsset: baseAssetAddr,
|
||||
quoteAsset: quoteAssetAddr,
|
||||
matcherFeeAsset: orionFeeAssetAddr,
|
||||
matcherFeeAsset: serviceFeeAssetAddr,
|
||||
amount: normalizeNumber(
|
||||
amount,
|
||||
INTERNAL_ORION_PRECISION,
|
||||
INTERNAL_PROTOCOL_PRECISION,
|
||||
BigNumber.ROUND_FLOOR,
|
||||
).toNumber(),
|
||||
price: normalizeNumber(
|
||||
price,
|
||||
INTERNAL_ORION_PRECISION,
|
||||
INTERNAL_PROTOCOL_PRECISION,
|
||||
BigNumber.ROUND_FLOOR,
|
||||
).toNumber(),
|
||||
matcherFee: normalizeNumber(
|
||||
matcherFee,
|
||||
INTERNAL_ORION_PRECISION,
|
||||
INTERNAL_PROTOCOL_PRECISION,
|
||||
BigNumber.ROUND_CEIL, // ROUND_CEIL because we don't want get "not enough fee" error
|
||||
).toNumber(),
|
||||
nonce,
|
||||
|
||||
@@ -2,7 +2,7 @@ import { BigNumber } from 'bignumber.js';
|
||||
BigNumber.config({ EXPONENTIAL_AT: 1e+9 });
|
||||
|
||||
export * as config from './config/index.js';
|
||||
export { default as OrionUnit } from './OrionUnit/index.js';
|
||||
export { default as Unit } from './Unit/index.js';
|
||||
export { default as Orion } from './Orion/index.js';
|
||||
export * as utils from './utils/index.js';
|
||||
export * as services from './services/index.js';
|
||||
|
||||
@@ -6,7 +6,7 @@ import cancelOrderSchema from './schemas/cancelOrderSchema.js';
|
||||
import orderBenefitsSchema from './schemas/orderBenefitsSchema.js';
|
||||
import errorSchema from './schemas/errorSchema.js';
|
||||
import placeAtomicSwapSchema from './schemas/placeAtomicSwapSchema.js';
|
||||
import { OrionAggregatorWS } from './ws/index.js';
|
||||
import { AggregatorWS } from './ws/index.js';
|
||||
import { atomicSwapHistorySchema } from './schemas/atomicSwapHistorySchema.js';
|
||||
import type { Exchange, SignedCancelOrderRequest, SignedCFDOrder, SignedOrder } from '../../types.js';
|
||||
import { pairConfigSchema } from './schemas/index.js';
|
||||
@@ -21,10 +21,10 @@ import orderSchema from './schemas/orderSchema.js';
|
||||
import { exchanges } from '../../constants/index.js';
|
||||
import { fetchWithValidation } from 'simple-typed-fetch';
|
||||
|
||||
class OrionAggregator {
|
||||
class Aggregator {
|
||||
private readonly apiUrl: string;
|
||||
|
||||
readonly ws: OrionAggregatorWS;
|
||||
readonly ws: AggregatorWS;
|
||||
|
||||
get api() {
|
||||
return this.apiUrl;
|
||||
@@ -36,12 +36,12 @@ class OrionAggregator {
|
||||
) {
|
||||
// const oaUrl = new URL(apiUrl);
|
||||
// const oaWsProtocol = oaUrl.protocol === 'https:' ? 'wss' : 'ws';
|
||||
// const orionAggregatorWsUrl = `${oaWsProtocol}://${oaUrl.host + (oaUrl.pathname === '/'
|
||||
// const aggregatorWsUrl = `${oaWsProtocol}://${oaUrl.host + (oaUrl.pathname === '/'
|
||||
// ? ''
|
||||
// : oaUrl.pathname)}/v1`;
|
||||
|
||||
this.apiUrl = httpAPIUrl;
|
||||
this.ws = new OrionAggregatorWS(httpToWS(wsAPIUrl));
|
||||
this.ws = new AggregatorWS(httpToWS(wsAPIUrl));
|
||||
|
||||
this.getHistoryAtomicSwaps = this.getHistoryAtomicSwaps.bind(this);
|
||||
this.getPairConfig = this.getPairConfig.bind(this);
|
||||
@@ -351,7 +351,7 @@ class OrionAggregator {
|
||||
);
|
||||
|
||||
/**
|
||||
* Get placed atomic swaps. Each atomic swap received from this list has a target chain corresponding to this Orion Aggregator
|
||||
* Get placed atomic swaps. Each atomic swap received from this list has a target chain corresponding to this Aggregator
|
||||
* @param sender Sender address
|
||||
* @returns Fetch promise
|
||||
*/
|
||||
@@ -364,4 +364,4 @@ class OrionAggregator {
|
||||
}
|
||||
export * as schemas from './schemas/index.js';
|
||||
export * as ws from './ws/index.js';
|
||||
export { OrionAggregator };
|
||||
export { Aggregator };
|
||||
@@ -71,7 +71,6 @@ const subOrderSchema = baseOrderSchema.extend({
|
||||
})),
|
||||
exchange: z.enum(exchanges),
|
||||
brokerAddress:
|
||||
// https://github.com/orionprotocol/orion-aggregator/blob/98f543e59b7bbf14d8db0417c6af5cf7575f3956/src/main/java/io/orionprotocol/aggregator/model/Exchange.java#L116
|
||||
z.enum(['ORION_BROKER', 'SELF_BROKER'])
|
||||
.or(z.custom<SelfBroker>((value) => {
|
||||
if (typeof value === 'string' && isSelfBroker(value)) {
|
||||
@@ -23,7 +23,6 @@ import { objectKeys } from '../../../utils/objectKeys.js';
|
||||
|
||||
const UNSUBSCRIBE = 'u';
|
||||
|
||||
// https://github.com/orionprotocol/orion-aggregator/tree/feature/OP-1752-symmetric-swap#swap-info-subscribe
|
||||
type SwapSubscriptionRequest = {
|
||||
// d: string, // swap request UUID, set by client side
|
||||
i: string // asset in
|
||||
@@ -162,7 +161,7 @@ const isSubType = (subType: string): subType is keyof Subscription => Object.val
|
||||
|
||||
const unknownMessageTypeRegex = /An unknown message type: '(.*)', json: (.*)/;
|
||||
const nonExistentMessageRegex = /Could not cancel nonexistent subscription: (.*)/;
|
||||
class OrionAggregatorWS {
|
||||
class AggregatorWS {
|
||||
private ws?: WebSocket | undefined;
|
||||
|
||||
// is used to make sure we do not need to renew ws subscription
|
||||
@@ -319,10 +318,10 @@ class OrionAggregatorWS {
|
||||
this.isClosedIntentionally = false;
|
||||
this.ws = new WebSocket(this.wsUrl);
|
||||
this.ws.onerror = (err) => {
|
||||
this.logger?.(`OrionAggregatorWS: ${err.message}`);
|
||||
this.logger?.(`AggregatorWS: ${err.message}`);
|
||||
};
|
||||
this.ws.onclose = () => {
|
||||
this.logger?.(`OrionAggregatorWS: connection closed ${this.isClosedIntentionally ? 'intentionally' : ''}`);
|
||||
this.logger?.(`AggregatorWS: connection closed ${this.isClosedIntentionally ? 'intentionally' : ''}`);
|
||||
if (!this.isClosedIntentionally) this.init(true);
|
||||
};
|
||||
this.ws.onopen = () => {
|
||||
@@ -342,12 +341,12 @@ class OrionAggregatorWS {
|
||||
}
|
||||
});
|
||||
}
|
||||
this.logger?.(`OrionAggregatorWS: connection opened${isReconnect ? ' (reconnect)' : ''}`);
|
||||
this.logger?.(`AggregatorWS: connection opened${isReconnect ? ' (reconnect)' : ''}`);
|
||||
};
|
||||
this.ws.onmessage = (e) => {
|
||||
const { data } = e;
|
||||
if (typeof data !== 'string') throw new Error('OrionAggregatorWS: received non-string message');
|
||||
this.logger?.(`OrionAggregatorWS: received message: ${data}`);
|
||||
if (typeof data !== 'string') throw new Error('AggregatorWS: received non-string message');
|
||||
this.logger?.(`AggregatorWS: received message: ${data}`);
|
||||
const rawJson: unknown = JSON.parse(data);
|
||||
|
||||
const messageSchema = z.union([
|
||||
@@ -389,9 +388,9 @@ class OrionAggregatorWS {
|
||||
console.warn(`You tried to subscribe to '${subscription}' with unknown payload '${jsonPayload}'. This is probably a bug in the code. Please be sure that you are subscribing to the existing subscription with the correct payload.`)
|
||||
} else {
|
||||
const subType = objectKeys(this.subscriptions).find((st) => this.subscriptions[st]?.[id]);
|
||||
if (subType === undefined) throw new Error(`OrionAggregatorWS: cannot find subscription type by id ${id}. Current subscriptions: ${JSON.stringify(this.subscriptions)}`);
|
||||
if (subType === undefined) throw new Error(`AggregatorWS: cannot find subscription type by id ${id}. Current subscriptions: ${JSON.stringify(this.subscriptions)}`);
|
||||
const sub = this.subscriptions[subType]?.[id];
|
||||
if (sub === undefined) throw new Error(`OrionAggregatorWS: cannot find subscription by id ${id}. Current subscriptions: ${JSON.stringify(this.subscriptions)}`);
|
||||
if (sub === undefined) throw new Error(`AggregatorWS: cannot find subscription by id ${id}. Current subscriptions: ${JSON.stringify(this.subscriptions)}`);
|
||||
if ('errorCb' in sub) {
|
||||
sub.errorCb(err.m);
|
||||
}
|
||||
@@ -658,7 +657,7 @@ class OrionAggregatorWS {
|
||||
|
||||
export * as schemas from './schemas/index.js';
|
||||
export {
|
||||
OrionAggregatorWS,
|
||||
AggregatorWS,
|
||||
SubscriptionType,
|
||||
UnsubscriptionType,
|
||||
MessageType,
|
||||
@@ -15,7 +15,7 @@ import {
|
||||
governancePoolsSchema,
|
||||
governancePoolSchema,
|
||||
} from './schemas/index.js';
|
||||
import type redeemOrderSchema from '../OrionAggregator/schemas/redeemOrderSchema.js';
|
||||
import type redeemOrderSchema from '../Aggregator/schemas/redeemOrderSchema.js';
|
||||
import { sourceAtomicHistorySchema, targetAtomicHistorySchema } from './schemas/atomicHistorySchema.js';
|
||||
import { makePartial } from '../../utils/index.js';
|
||||
import type { networkCodes } from '../../constants/index.js';
|
||||
@@ -63,7 +63,7 @@ type CfdHistoryQuery = {
|
||||
page?: number
|
||||
limit?: number
|
||||
} & Partial<Record<string, string | number>>
|
||||
class OrionBlockchain {
|
||||
class BlockchainService {
|
||||
private readonly apiUrl: string;
|
||||
|
||||
get api() {
|
||||
@@ -112,7 +112,7 @@ class OrionBlockchain {
|
||||
this.getGovernancePool = this.getGovernancePool.bind(this);
|
||||
}
|
||||
|
||||
get orionBlockchainWsUrl() {
|
||||
get blockchainServiceWsUrl() {
|
||||
return `${this.apiUrl}/`;
|
||||
}
|
||||
|
||||
@@ -356,8 +356,8 @@ class OrionBlockchain {
|
||||
);
|
||||
|
||||
/**
|
||||
* Sender is user address in source Orion Blockchain instance \
|
||||
* Receiver is user address in target Orion Blockchain instance
|
||||
* Sender is user address in source BlockchainService instance \
|
||||
* Receiver is user address in target BlockchainService instance
|
||||
*/
|
||||
getAtomicSwapHistory = (query: AtomicSwapHistorySourceQuery | AtomicSwapHistoryTargetQuery) => {
|
||||
const url = new URL(`${this.apiUrl}/api/atomic/history/`);
|
||||
@@ -446,4 +446,4 @@ class OrionBlockchain {
|
||||
}
|
||||
|
||||
export * as schemas from './schemas/index.js';
|
||||
export { OrionBlockchain };
|
||||
export { BlockchainService };
|
||||
@@ -1,4 +1,4 @@
|
||||
export * as orionAggregator from './OrionAggregator/index.js';
|
||||
export * as orionBlockchain from './OrionBlockchain/index.js';
|
||||
export * as aggregator from './Aggregator/index.js';
|
||||
export * as blockchainService from './BlockchainService/index.js';
|
||||
export * as priceFeed from './PriceFeed/index.js';
|
||||
export * as referralSystem from './ReferralSystem/index.js';
|
||||
|
||||
12
src/types.ts
12
src/types.ts
@@ -263,33 +263,33 @@ export enum HistoryTransactionStatus {
|
||||
CANCELLED = 'Cancelled',
|
||||
}
|
||||
|
||||
export type VerboseOrionUnitConfig = {
|
||||
export type VerboseUnitConfig = {
|
||||
// env?: string;
|
||||
// api: string;
|
||||
chainId: SupportedChainId
|
||||
nodeJsonRpc: string
|
||||
services: {
|
||||
orionBlockchain: {
|
||||
blockchainService: {
|
||||
http: string
|
||||
// For example:
|
||||
// http://localhost:3001/,
|
||||
// http://10.123.34.23:3001/,
|
||||
// https://blockchain.orionprotocol.io/
|
||||
// https://blockchain:3001/
|
||||
}
|
||||
orionAggregator: {
|
||||
aggregator: {
|
||||
http: string
|
||||
ws: string
|
||||
// For example:
|
||||
// http://localhost:3002/,
|
||||
// http://10.34.23.5:3002/,
|
||||
// shttps://aggregator.orionprotocol.io/
|
||||
// https://aggregator:3002/
|
||||
}
|
||||
priceFeed: {
|
||||
api: string
|
||||
// For example:
|
||||
// http://localhost:3003/,
|
||||
// http://10.23.5.11:3003/,
|
||||
// https://price-feed.orionprotocol.io/
|
||||
// https://price-feed:3003/
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { BigNumber } from 'bignumber.js';
|
||||
import { FILL_ORDERS_GAS_LIMIT } from '../constants/index.js';
|
||||
import calculateNetworkFeeInFeeAsset from './calculateNetworkFeeInFeeAsset.js';
|
||||
import calculateOrionFeeInFeeAsset from './calculateOrionFeeInFeeAsset.js';
|
||||
import calculateServiceFeeInFeeAsset from './calculateServiceFeeInFeeAsset.js';
|
||||
|
||||
const calculateFeeInFeeAsset = (
|
||||
amount: BigNumber.Value,
|
||||
@@ -11,7 +11,7 @@ const calculateFeeInFeeAsset = (
|
||||
gasPriceGwei: BigNumber.Value,
|
||||
feePercent: BigNumber.Value,
|
||||
) => {
|
||||
const orionFeeInFeeAsset = calculateOrionFeeInFeeAsset(
|
||||
const serviceFeeInFeeAsset = calculateServiceFeeInFeeAsset(
|
||||
amount,
|
||||
feeAssetPriceInOrn,
|
||||
baseAssetPriceInOrn,
|
||||
@@ -25,9 +25,9 @@ const calculateFeeInFeeAsset = (
|
||||
);
|
||||
|
||||
return {
|
||||
orionFeeInFeeAsset,
|
||||
serviceFeeInFeeAsset,
|
||||
networkFeeInFeeAsset,
|
||||
totalFeeInFeeAsset: new BigNumber(orionFeeInFeeAsset)
|
||||
totalFeeInFeeAsset: new BigNumber(serviceFeeInFeeAsset)
|
||||
.plus(networkFeeInFeeAsset)
|
||||
.toString(),
|
||||
};
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { BigNumber } from 'bignumber.js';
|
||||
|
||||
export default function calculateOrionFeeInFeeAsset(
|
||||
export default function calculateServiceFeeInFeeAsset(
|
||||
amount: BigNumber.Value,
|
||||
feeAssetPriceInOrn: BigNumber.Value,
|
||||
baseAssetPriceInOrn: BigNumber.Value,
|
||||
@@ -2,17 +2,17 @@ import { ethers } from 'ethers';
|
||||
import type { Source } from '../types.js';
|
||||
|
||||
export default function getAvailableFundsSources(
|
||||
expenseType: 'amount' | 'network_fee' | 'orion_fee',
|
||||
expenseType: 'amount' | 'network_fee' | 'service_fee',
|
||||
assetAddress: string,
|
||||
route: 'aggregator' | 'orion_pool',
|
||||
route: 'aggregator' | 'pool',
|
||||
): Source[] {
|
||||
switch (route) {
|
||||
case 'aggregator':
|
||||
if (assetAddress === ethers.constants.AddressZero) return ['exchange']; // We can't take native crypto from wallet
|
||||
return ['exchange', 'wallet']; // We can take any token amount from exchange + wallet. Order is important!
|
||||
case 'orion_pool':
|
||||
case 'pool':
|
||||
if (expenseType === 'network_fee') return ['wallet']; // Network fee is always taken from wallet
|
||||
return ['exchange', 'wallet']; // We can take any token amount from exchange + wallet (specify 'value' for 'orion_pool'). Order is important!
|
||||
return ['exchange', 'wallet']; // We can take any token amount from exchange + wallet (specify 'value' for 'pool'). Order is important!
|
||||
default:
|
||||
throw new Error('Unknown route item');
|
||||
}
|
||||
|
||||
@@ -2,12 +2,12 @@ import type { Exchange } from '@orionprotocol/contracts/lib/ethers-v5/index.js';
|
||||
import { ERC20__factory } from '@orionprotocol/contracts/lib/ethers-v5/index.js';
|
||||
import type { BigNumber } from 'bignumber.js';
|
||||
import { ethers } from 'ethers';
|
||||
import { INTERNAL_ORION_PRECISION, NATIVE_CURRENCY_PRECISION } from '../constants/index.js';
|
||||
import type { OrionAggregator } from '../services/OrionAggregator/index.js';
|
||||
import { INTERNAL_PROTOCOL_PRECISION, NATIVE_CURRENCY_PRECISION } from '../constants/index.js';
|
||||
import type { Aggregator } from '../services/Aggregator/index.js';
|
||||
import denormalizeNumber from './denormalizeNumber.js';
|
||||
|
||||
export default async function getBalance(
|
||||
orionAggregator: OrionAggregator,
|
||||
aggregator: Aggregator,
|
||||
assetName: string,
|
||||
assetAddress: string,
|
||||
walletAddress: string,
|
||||
@@ -31,8 +31,8 @@ export default async function getBalance(
|
||||
denormalizedAssetInWalletBalance = denormalizeNumber(assetWalletBalance, NATIVE_CURRENCY_PRECISION);
|
||||
}
|
||||
const assetContractBalance = await exchangeContract.getBalance(assetAddress, walletAddress);
|
||||
const denormalizedAssetInContractBalance = denormalizeNumber(assetContractBalance, INTERNAL_ORION_PRECISION);
|
||||
const denormalizedAssetLockedBalanceResult = await orionAggregator.getLockedBalance(walletAddress, assetName);
|
||||
const denormalizedAssetInContractBalance = denormalizeNumber(assetContractBalance, INTERNAL_PROTOCOL_PRECISION);
|
||||
const denormalizedAssetLockedBalanceResult = await aggregator.getLockedBalance(walletAddress, assetName);
|
||||
if (denormalizedAssetLockedBalanceResult.isErr()) {
|
||||
throw new Error(denormalizedAssetLockedBalanceResult.error.message);
|
||||
}
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
import type { Exchange } from '@orionprotocol/contracts/lib/ethers-v5/index.js';
|
||||
import type { BigNumber } from 'bignumber.js';
|
||||
import type { ethers } from 'ethers';
|
||||
import type { OrionAggregator } from '../services/OrionAggregator/index.js';
|
||||
import type { Aggregator } from '../services/Aggregator/index.js';
|
||||
import getBalance from './getBalance.js';
|
||||
|
||||
export default async (
|
||||
balancesRequired: Partial<Record<string, string>>,
|
||||
orionAggregator: OrionAggregator,
|
||||
aggregator: Aggregator,
|
||||
walletAddress: string,
|
||||
exchangeContract: Exchange,
|
||||
provider: ethers.providers.Provider,
|
||||
@@ -16,7 +16,7 @@ export default async (
|
||||
.map(async ([assetName, assetAddress]) => {
|
||||
if (assetAddress === undefined) throw new Error(`Asset address of ${assetName} not found`);
|
||||
const balance = await getBalance(
|
||||
orionAggregator,
|
||||
aggregator,
|
||||
assetName,
|
||||
assetAddress,
|
||||
walletAddress,
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
export { default as calculateFeeInFeeAsset } from './calculateFeeInFeeAsset.js';
|
||||
export { default as calculateNetworkFee } from './calculateNetworkFee.js';
|
||||
export { default as calculateNetworkFeeInFeeAsset } from './calculateNetworkFeeInFeeAsset.js';
|
||||
export { default as calculateOrionFeeInFeeAsset } from './calculateOrionFeeInFeeAsset.js';
|
||||
export { default as calculateOrionFeeInFeeAsset } from './calculateServiceFeeInFeeAsset.js';
|
||||
export { default as checkIsToken } from './checkIsToken.js';
|
||||
export { default as generateSecret } from './generateSecret.js';
|
||||
export { default as denormalizeNumber } from './denormalizeNumber.js';
|
||||
|
||||
Reference in New Issue
Block a user