Semantics improvements

This commit is contained in:
Aleksandr Kraiz
2023-05-16 23:21:45 +04:00
parent 188e7bb317
commit cd4eff76d3
88 changed files with 419 additions and 478 deletions

View File

@@ -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,
}
}, {});

View File

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

View File

@@ -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] ?? []),