Skip to content

Commit

Permalink
Merge branch 'refs/heads/main' into feat/OP-4308-cross-chain-swap
Browse files Browse the repository at this point in the history
# Conflicts:
#	package-lock.json
#	package.json
  • Loading branch information
TheJuze committed Jun 3, 2024
2 parents ab4a674 + 2c89b2e commit f793acd
Show file tree
Hide file tree
Showing 10 changed files with 36 additions and 47 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@orionprotocol/sdk",
"version": "0.22.0-rc19",
"version": "0.22.0-rc20",
"description": "Orion Protocol SDK",
"main": "./lib/index.cjs",
"module": "./lib/index.js",
Expand Down
20 changes: 5 additions & 15 deletions src/Unit/Exchange/getSwapInfo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import type { BlockchainService } from '../../services/BlockchainService/index.j
import { calculateFeeInFeeAsset, denormalizeNumber, getNativeCryptocurrencyName } from '../../utils/index.js';

export type GetSwapInfoParams = {
type: 'exactSpend' | 'exactReceive'
assetIn: string
assetOut: string
amount: BigNumber.Value
Expand All @@ -18,12 +17,12 @@ export type GetSwapInfoParams = {
options?: {
instantSettlement?: boolean
poolOnly?: boolean
},
walletAddress?: string,
}
walletAddress?: string
isTradeBuy?: boolean
}

export default async function getSwapInfo({
type,
assetIn,
assetOut,
amount,
Expand All @@ -32,6 +31,7 @@ export default async function getSwapInfo({
aggregator,
options,
walletAddress,
isTradeBuy = false,
}: GetSwapInfoParams) {
if (amount === '') throw new Error('Amount can not be empty');
if (assetIn === '') throw new Error('AssetIn can not be empty');
Expand Down Expand Up @@ -61,31 +61,21 @@ export default async function getSwapInfo({
}

const swapInfo = await simpleFetch(aggregator.getSwapInfo)(
type,
assetIn,
assetOut,
amountBN.toString(),
options?.instantSettlement,
options?.poolOnly !== undefined && options.poolOnly
? 'pools'
: undefined,
isTradeBuy,
);

const { exchanges: swapExchanges } = swapInfo;
const { factories } = await simpleFetch(blockchainService.getPoolsConfig)();
const poolExchangesList = factories !== undefined ? Object.keys(factories) : [];
const [firstSwapExchange] = swapExchanges;

// if (swapInfo.type === 'exactReceive' && amountBN.lt(swapInfo.minAmountOut)) {
// throw new Error(`Amount is too low. Min amountOut is ${swapInfo.minAmountOut} ${assetOut}`);
// }

// if (swapInfo.type === 'exactSpend' && amountBN.lt(swapInfo.minAmountIn)) {
// throw new Error(`Amount is too low. Min amountIn is ${swapInfo.minAmountIn} ${assetIn}`);
// }

// if (swapInfo.orderInfo === null) throw new Error(swapInfo.executionInfo);

let route: 'pool' | 'aggregator';
if (options?.poolOnly !== undefined && options.poolOnly) {
route = 'pool';
Expand Down
20 changes: 10 additions & 10 deletions src/Unit/Exchange/swapLimit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@ import type { SingleSwap } from '../../types.js';
import { must, safeGet } from '../../utils/safeGetters.js';

export type SwapLimitParams = {
type: 'exactSpend' | 'exactReceive'
assetIn: string
assetOut: string
price: BigNumber.Value
Expand All @@ -39,6 +38,7 @@ export type SwapLimitParams = {
route?: 'aggregator' | 'pool'
}
}
isTradeBuy?: boolean
}

type AggregatorOrder = {
Expand All @@ -62,7 +62,6 @@ const isValidSingleSwap = (singleSwap: Omit<SingleSwap, 'factory'> & { factory:
}

export default async function swapLimit({
type,
assetIn,
assetOut,
price,
Expand All @@ -71,6 +70,7 @@ export default async function swapLimit({
signer,
unit,
options,
isTradeBuy = false,
}: SwapLimitParams): Promise<Swap> {
if (options?.developer) options.logger?.('YOU SPECIFIED A DEVELOPER OPTIONS. BE CAREFUL!');
if (amount === '') throw new Error('Amount can not be empty');
Expand Down Expand Up @@ -142,14 +142,14 @@ export default async function swapLimit({
);

const swapInfo = await simpleFetch(aggregator.getSwapInfo)(
type,
assetIn,
assetOut,
amountBN.toString(),
options?.instantSettlement,
options?.poolOnly !== undefined && options.poolOnly
? 'pools'
: undefined,
isTradeBuy,
);

const { exchanges: swapExchanges, exchangeContractPath } = swapInfo;
Expand All @@ -158,11 +158,11 @@ export default async function swapLimit({

if (swapExchanges.length > 0) options?.logger?.(`Swap exchanges: ${swapExchanges.join(', ')}`);

if (swapInfo.type === 'exactReceive' && amountBN.lt(swapInfo.minAmountOut)) {
if (swapInfo?.isTradeBuy && amountBN.lt(swapInfo.minAmountOut)) {
throw new Error(`Amount is too low. Min amountOut is ${swapInfo.minAmountOut} ${assetOut}`);
}

if (swapInfo.type === 'exactSpend' && amountBN.lt(swapInfo.minAmountIn)) {
if (!(swapInfo?.isTradeBuy) && amountBN.lt(swapInfo.minAmountIn)) {
throw new Error(`Amount is too low. Min amountIn is ${swapInfo.minAmountIn} ${assetIn}`);
}

Expand Down Expand Up @@ -204,9 +204,9 @@ export default async function swapLimit({

options?.logger?.(`Safe price is ${swapInfo.orderInfo.safePrice} ${quoteAssetName}`);
// BTEMP — better than or equal market price
const priceIsBTEMP = type === 'exactSpend'
? priceBN.lte(swapInfo.orderInfo.safePrice)
: priceBN.gte(swapInfo.orderInfo.safePrice);
const priceIsBTEMP = isTradeBuy
? priceBN.gte(swapInfo.orderInfo.safePrice)
: priceBN.lte(swapInfo.orderInfo.safePrice);

options?.logger?.(`Your price ${priceBN.toString()} is ${priceIsBTEMP ? 'better than or equal' : 'worse than'} market price ${swapInfo.orderInfo.safePrice}`);

Expand Down Expand Up @@ -250,7 +250,7 @@ export default async function swapLimit({
if (factoryAddress !== undefined) options?.logger?.(`Factory address is ${factoryAddress}. Exchange is ${firstSwapExchange}`);
}

const amountSpend = swapInfo.type === 'exactSpend'
const amountSpend = !(swapInfo?.isTradeBuy)
? swapInfo.amountIn
: new BigNumber(swapInfo.orderInfo.amount).multipliedBy(swapInfo.orderInfo.safePrice)

Expand All @@ -265,7 +265,7 @@ export default async function swapLimit({
sources: getAvailableSources('amount', assetInAddress, 'pool'),
});

const amountReceive = swapInfo.type === 'exactReceive'
const amountReceive = swapInfo?.isTradeBuy
? swapInfo.amountOut
: new BigNumber(swapInfo.orderInfo.amount).multipliedBy(swapInfo.orderInfo.safePrice)
const amountSpendBlockchainParam = normalizeNumber(
Expand Down
12 changes: 6 additions & 6 deletions src/Unit/Exchange/swapMarket.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,6 @@ const isValidSingleSwap = (singleSwap: Omit<SingleSwap, 'factory'> & { factory:
}

export default async function swapMarket({
type,
assetIn,
assetOut,
amount,
Expand All @@ -55,6 +54,7 @@ export default async function swapMarket({
signer,
unit,
options,
isTradeBuy = false,
}: SwapMarketParams): Promise<Swap> {
if (options?.developer) options.logger?.('YOU SPECIFIED A DEVELOPER OPTIONS. BE CAREFUL!');

Expand Down Expand Up @@ -128,14 +128,14 @@ export default async function swapMarket({
);

const swapInfo = await simpleFetch(aggregator.getSwapInfo)(
type,
assetIn,
assetOut,
amountBN.toString(),
options?.instantSettlement,
options?.poolOnly !== undefined && options.poolOnly
? 'pools'
: undefined,
isTradeBuy,
);

const { exchanges: swapExchanges, exchangeContractPath } = swapInfo;
Expand All @@ -144,11 +144,11 @@ export default async function swapMarket({

if (swapExchanges.length > 0) options?.logger?.(`Swap exchanges: ${swapExchanges.join(', ')}`);

if (swapInfo.type === 'exactReceive' && amountBN.lt(swapInfo.minAmountOut)) {
if (swapInfo?.isTradeBuy && amountBN.lt(swapInfo.minAmountOut)) {
throw new Error(`Amount is too low. Min amountOut is ${swapInfo.minAmountOut} ${assetOut}`);
}

if (swapInfo.type === 'exactSpend' && amountBN.lt(swapInfo.minAmountIn)) {
if (!(swapInfo?.isTradeBuy) && amountBN.lt(swapInfo.minAmountIn)) {
throw new Error(`Amount is too low. Min amountIn is ${swapInfo.minAmountIn} ${assetIn}`);
}

Expand Down Expand Up @@ -206,7 +206,7 @@ export default async function swapMarket({
.multipliedBy(new BigNumber(1).plus(percent))
.toString();

const amountSpend = swapInfo.type === 'exactSpend' ? swapInfo.amountIn : amountInWithSlippage;
const amountSpend = swapInfo?.isTradeBuy ? amountInWithSlippage : swapInfo.amountIn;

balanceGuard.registerRequirement({
reason: 'Amount spend',
Expand All @@ -219,7 +219,7 @@ export default async function swapMarket({
sources: getAvailableSources('amount', assetInAddress, 'pool'),
});

const amountReceive = swapInfo.type === 'exactReceive' ? swapInfo.amountOut : amountOutWithSlippage;
const amountReceive = swapInfo?.isTradeBuy ? amountOutWithSlippage : swapInfo.amountOut;
const amountSpendBlockchainParam = normalizeNumber(
amountSpend,
INTERNAL_PROTOCOL_PRECISION,
Expand Down
5 changes: 3 additions & 2 deletions src/services/Aggregator/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -315,21 +315,22 @@ class Aggregator {
);

getSwapInfo = (
type: 'exactSpend' | 'exactReceive',
assetIn: string,
assetOut: string,
amount: string,
instantSettlement?: boolean,
exchanges?: string[] | 'cex' | 'pools',
isTradeBuy?: boolean,
) => {
const url = new URL(`${this.apiUrl}/api/v1/swap`);
url.searchParams.append('assetIn', assetIn);
url.searchParams.append('assetOut', assetOut);
if (type === 'exactSpend') {
if (isTradeBuy !== true) {
url.searchParams.append('amountIn', amount);
} else {
url.searchParams.append('amountOut', amount);
}

if (exchanges !== undefined) {
if (Array.isArray(exchanges)) {
exchanges.forEach((exchange) => {
Expand Down
4 changes: 2 additions & 2 deletions src/services/Aggregator/schemas/swapInfoSchema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ const swapInfoByAmountIn = swapInfoBase.extend({
marketAmountIn: z.null(),
}).transform((val) => ({
...val,
type: 'exactSpend' as const,
isTradeBuy: false as const,
}));

const swapInfoByAmountOut = swapInfoBase.extend({
Expand All @@ -74,7 +74,7 @@ const swapInfoByAmountOut = swapInfoBase.extend({
marketAmountIn: z.number().nullable(),
}).transform((val) => ({
...val,
type: 'exactReceive' as const,
isTradeBuy: true as const,
}));

const swapInfoSchema = swapInfoByAmountIn.or(swapInfoByAmountOut);
Expand Down
10 changes: 5 additions & 5 deletions src/services/Aggregator/ws/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -551,19 +551,19 @@ class AggregatorWS {
autoSlippage: json.sl,
};

switch (json.k) { // kind
case 'exactSpend':
switch (json.tb) { // isTradeBuy
case false:
this.subscriptions[SubscriptionType.SWAP_SUBSCRIBE]?.[json.S]?.callback({
kind: json.k,
isTradeBuy: false,
marketAmountOut: json.mo,
availableAmountIn: json.aa,
...baseSwapInfo,
});

break;
case 'exactReceive':
case true:
this.subscriptions[SubscriptionType.SWAP_SUBSCRIBE]?.[json.S]?.callback({
kind: json.k,
isTradeBuy: true,
...baseSwapInfo,
marketAmountIn: json.mi,
availableAmountOut: json.aao,
Expand Down
4 changes: 2 additions & 2 deletions src/services/Aggregator/ws/schemas/swapInfoSchema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,15 +59,15 @@ const swapInfoSchemaByAmountIn = swapInfoSchemaBase.extend({
aa: z.number(), // available amount in
}).transform((content) => ({
...content,
k: 'exactSpend' as const,
tb: false as const, // isTradeBuy
}));

const swapInfoSchemaByAmountOut = swapInfoSchemaBase.extend({
mi: z.number().optional(), // market amount in
aao: z.number(), // available amount out
}).transform((content) => ({
...content,
k: 'exactReceive' as const,
tb: true as const, // isTradeBuy
}));

const swapInfoSchema = z.union([
Expand Down
4 changes: 2 additions & 2 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -247,13 +247,13 @@ export type SwapInfoBase = {
}

export type SwapInfoByAmountIn = SwapInfoBase & {
kind: 'exactSpend'
isTradeBuy: false
availableAmountIn?: number | undefined
marketAmountOut?: number | undefined
}

export type SwapInfoByAmountOut = SwapInfoBase & {
kind: 'exactReceive'
isTradeBuy: true
marketAmountIn?: number | undefined
availableAmountOut?: number | undefined
}
Expand Down
2 changes: 0 additions & 2 deletions src/utils/parseExchangeTradeTransaction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,13 @@ const swapThroughOrionPoolSchema = z.object({
z.bigint(), // amount_spend
z.bigint(), // amount_receive
z.string().refine(ethers.isAddress).array().nonempty(), // path
z.boolean(), // is_exact_spend
]),
}).transform((data) => ({
name: data.name,
args: {
amount_spend: data.args[0],
amount_receive: data.args[1],
path: data.args[2],
is_exact_spend: data.args[3],
},
}));

Expand Down

0 comments on commit f793acd

Please sign in to comment.