Skip to content

Commit

Permalink
updating aggregator
Browse files Browse the repository at this point in the history
  • Loading branch information
abstract829 committed Jul 25, 2024
1 parent 4e7b0fe commit 538d3a9
Show file tree
Hide file tree
Showing 9 changed files with 238 additions and 139 deletions.
26 changes: 13 additions & 13 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,20 +26,20 @@
"@polkadot/types": "^10.12.6",
"@reduxjs/toolkit": "^2.2.1",
"@scio-labs/use-inkathon": "^0.8.1",
"@soroban-react/chains": "9.1.12",
"@soroban-react/connect-button": "9.1.12",
"@soroban-react/contracts": "9.1.12",
"@soroban-react/core": "9.1.12",
"@soroban-react/events": "9.1.12",
"@soroban-react/freighter": "9.1.12",
"@soroban-react/hana": "9.1.12",
"@soroban-react/lobstr": "9.1.12",
"@soroban-react/types": "9.1.12",
"@soroban-react/utils": "9.1.12",
"@soroban-react/wallet-data": "9.1.12",
"@soroban-react/xbull": "9.1.12",
"@soroban-react/chains": "9.1.13",
"@soroban-react/connect-button": "9.1.13",
"@soroban-react/contracts": "9.1.13",
"@soroban-react/core": "9.1.13",
"@soroban-react/events": "9.1.13",
"@soroban-react/freighter": "9.1.13",
"@soroban-react/hana": "9.1.13",
"@soroban-react/lobstr": "9.1.13",
"@soroban-react/types": "9.1.13",
"@soroban-react/utils": "9.1.13",
"@soroban-react/wallet-data": "9.1.13",
"@soroban-react/xbull": "9.1.13",
"@stellar/freighter-api": "1.7.1",
"@stellar/stellar-sdk": "11.3.0",
"@stellar/stellar-sdk": "12.2.0",
"@types/qs": "^6.9.7",
"@types/react": "18.2.33",
"@types/react-dom": "18.2.14",
Expand Down
5 changes: 2 additions & 3 deletions src/functions/generateRoute.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ export const useRouterSDK = () => {
const router = useMemo(() => {
const protocols = [Protocols.SOROSWAP];

if (isAggregator) protocols.push(Protocols.PHOENIX);
// if (isAggregator) protocols.push(Protocols.PHOENIX);

return new Router({
getPairsFns: shouldUseBackend
Expand All @@ -53,7 +53,7 @@ export const useRouterSDK = () => {
network,
maxHops,
});
}, [network, maxHops, isAggregator]);
}, [network, maxHops]);

const fromAddressToToken = (address: string) => {
return new Token(network, address, 18);
Expand Down Expand Up @@ -84,7 +84,6 @@ export const useRouterSDK = () => {
return router.routeSplit(currencyAmount, quoteCurrency, tradeType);
}

// console.log('returning route');
return router.route(currencyAmount, quoteCurrency, tradeType, factory, sorobanContext as any);
};

Expand Down
28 changes: 14 additions & 14 deletions src/helpers/aggregator/index.ts
Original file line number Diff line number Diff line change
@@ -1,23 +1,22 @@
import { Address, nativeToScVal, xdr } from "@stellar/stellar-sdk";
import { Address, nativeToScVal, xdr } from '@stellar/stellar-sdk';

export interface DexDistribution {
protocol_id: string;
path: string[],
parts: number,
is_exact_in: boolean,
path: string[];
parts: number;
is_exact_in: boolean;
}

export const dexDistributionParser = (dexDistributionRaw: DexDistribution[]) : xdr.ScVal => {

export const dexDistributionParser = (dexDistributionRaw: DexDistribution[]): xdr.ScVal => {
const dexDistributionScVal = dexDistributionRaw.map((distribution) => {
return xdr.ScVal.scvMap([
new xdr.ScMapEntry({
key: xdr.ScVal.scvSymbol('is_exact_in'),
val: xdr.ScVal.scvBool(distribution.is_exact_in),
}),
// new xdr.ScMapEntry({
// key: xdr.ScVal.scvSymbol('is_exact_in'),
// val: xdr.ScVal.scvBool(distribution.is_exact_in),
// }),
new xdr.ScMapEntry({
key: xdr.ScVal.scvSymbol('parts'),
val: nativeToScVal(distribution.parts, {type: "i128"}),
val: nativeToScVal(distribution.parts, { type: 'i128' }),
}),
new xdr.ScMapEntry({
key: xdr.ScVal.scvSymbol('path'),
Expand All @@ -30,7 +29,8 @@ export const dexDistributionParser = (dexDistributionRaw: DexDistribution[]) : x
]);
});

return xdr.ScVal.scvVec(dexDistributionScVal)
}
return xdr.ScVal.scvVec(dexDistributionScVal);
};

export const hasDistribution = (trade: any): trade is { distribution: DexDistribution[] } => trade && 'distribution' in trade;
export const hasDistribution = (trade: any): trade is { distribution: DexDistribution[] } =>
trade && 'distribution' in trade;
6 changes: 3 additions & 3 deletions src/hooks/useAggregator.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,13 @@ export const useAggregator = () => {

if (activeChain?.id == 'mainnet') {
//TODO: Add mainnet aggregator address
setAddress('CD4NUEFTQU53SM7LPAQX5RHJOWOLOHRBM4HCNGA7UBQJ6MPIJNVGYEVL');
setAddress('CA4VZX7N577XGPSKDG4RT24CZ6XGR37TM2652SO2AASERVUWP72N4UGZ');
setIsAggregatorEnabled(false && shouldUseAggregator);
} else if (activeChain?.id == 'testnet') {
setAddress('CD4NUEFTQU53SM7LPAQX5RHJOWOLOHRBM4HCNGA7UBQJ6MPIJNVGYEVL');
setAddress('CA4VZX7N577XGPSKDG4RT24CZ6XGR37TM2652SO2AASERVUWP72N4UGZ');
setIsAggregatorEnabled(true && shouldUseAggregator);
} else {
setAddress('CD4NUEFTQU53SM7LPAQX5RHJOWOLOHRBM4HCNGA7UBQJ6MPIJNVGYEVL');
setAddress('CA4VZX7N577XGPSKDG4RT24CZ6XGR37TM2652SO2AASERVUWP72N4UGZ');
setIsAggregatorEnabled(false && shouldUseAggregator);
}
}, [activeChain?.id, sorobanContext]);
Expand Down
2 changes: 2 additions & 0 deletions src/hooks/useAggregatorCallback.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ export enum AggregatorMethod {
SWAP = 'swap',
GET_PROTOCOLS = 'get_protocols',
IS_PROTOCOL_PAUSED = 'is_protocol_paused',
SWAP_EXACT_IN = 'swap_exact_tokens_for_tokens',
SWAP_EXACT_OUT = 'swap_tokens_for_exact_tokens',
}

// fn swap(
Expand Down
46 changes: 34 additions & 12 deletions src/hooks/useBestTrade.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { useEffect, useMemo, useState } from 'react';
import { TradeType as SdkTradeType } from 'soroswap-router-sdk';
import { InterfaceTrade, QuoteState, TradeState, TradeType } from 'state/routing/types';
import useSWR from 'swr';
import { useAggregator } from './useAggregator';

const TRADE_NOT_FOUND = {
state: TradeState.NO_ROUTE_FOUND,
Expand Down Expand Up @@ -77,6 +78,8 @@ export function useBestTrade(
const [inputAmount, setInputAmount] = useState<CurrencyAmount | undefined>();
const [outputAmount, setOutputAmount] = useState<CurrencyAmount | undefined>();

const { isEnabled: isAggregatorEnabled } = useAggregator();

useEffect(() => {
if (!data || !currencyIn || !currencyOut) return;

Expand Down Expand Up @@ -104,22 +107,41 @@ export function useBestTrade(
const result = data.trade as {
amountInMax: string;
amountOut: string;
amountIn: string;
amountOutMin: string;
path: string[];
};

setInputAmount({
value: result?.amountInMax,
currency: currencyIn,
});

setOutputAmount({
value: result?.amountOut,
currency: currencyOut,
});

setExpectedAmount(result?.amountInMax);
if (isAggregatorEnabled) {
/*Work around for the aggregator as routeSplit only returns
amountIn and amountOutMin - we should fix this in the router-sdk
*/

setInputAmount({
value: result?.amountOutMin,
currency: currencyIn,
});
setOutputAmount({
value: result?.amountIn,
currency: currencyOut,
});

setExpectedAmount(result?.amountOutMin);
} else {
setInputAmount({
value: result?.amountInMax,
currency: currencyIn,
});

setOutputAmount({
value: result?.amountOut,
currency: currencyOut,
});

setExpectedAmount(result?.amountInMax);
}
}
}, [data, currencyIn, currencyOut, tradeType]);
}, [data, currencyIn, currencyOut, tradeType, isAggregatorEnabled]);

const trade: InterfaceTrade = useMemo(() => {
const baseTrade = {
Expand Down
34 changes: 26 additions & 8 deletions src/hooks/useSwapCallback.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,11 @@ export const getSwapAmounts = ({
const routerMethod =
tradeType == TradeType.EXACT_INPUT ? RouterMethod.SWAP_EXACT_IN : RouterMethod.SWAP_EXACT_OUT;

const aggregatorMethod =
tradeType == TradeType.EXACT_INPUT
? AggregatorMethod.SWAP_EXACT_IN
: AggregatorMethod.SWAP_EXACT_OUT;

const factorLess = BigNumber(100).minus(allowedSlippage).dividedBy(100);
const factorMore = BigNumber(100).plus(allowedSlippage).dividedBy(100);

Expand All @@ -82,7 +87,7 @@ export const getSwapAmounts = ({
? BigNumber(outputAmount).multipliedBy(factorLess).decimalPlaces(0)
: BigNumber(inputAmount).multipliedBy(factorMore).decimalPlaces(0);

return { amount0, amount1, routerMethod };
return { amount0, amount1, routerMethod, aggregatorMethod };
};

export type SuccessfullSwapResponse = StellarSdk.SorobanRpc.Api.GetSuccessfulTransactionResponse &
Expand Down Expand Up @@ -113,7 +118,7 @@ export function useSwapCallback(
if (!address || !activeChain) throw new Error('wallet must be connected to swap');
if (!trade.tradeType) throw new Error('tradeType must be defined');

const { amount0, amount1, routerMethod } = getSwapAmounts({
const { amount0, amount1, routerMethod, aggregatorMethod } = getSwapAmounts({
tradeType: trade.tradeType,
inputAmount: trade.inputAmount?.value as string,
outputAmount: trade.outputAmount?.value as string,
Expand All @@ -128,22 +133,34 @@ export function useSwapCallback(
console.log('USING AGGREGATOR');
if (!isUsingAggregator) throw Error('Non distribution');
const dexDistributionScValVec = dexDistributionParser(trade?.distribution);
console.log('🚀 « dexDistributionScValVec:', dexDistributionScValVec);

console.log({
aggparams: [
trade.inputAmount?.currency?.contract, //token_in
trade.outputAmount?.currency?.contract, //token_out
amount0, // amount_in - amount_out
amount1, // amount_out_min - amount_in_max
trade?.distribution, // proxy_addresses: Vec<ProxyAddressPair>,
address, //admin: Address,
getCurrentTimePlusOneHour(), //deadline
],
});

const aggregatorSwapParams: StellarSdk.xdr.ScVal[] = [
new StellarSdk.Address(trade.inputAmount?.currency.contract ?? '').toScVal(), //_from_token: Address,
new StellarSdk.Address(trade.outputAmount?.currency.contract ?? '').toScVal(), //_dest_token: Address,
amount0ScVal,
amount1ScVal,
new StellarSdk.Address(trade.inputAmount?.currency?.contract ?? '').toScVal(), //token_in
new StellarSdk.Address(trade.outputAmount?.currency?.contract ?? '').toScVal(), //token_out
amount0ScVal, // amount_in - amount_out
amount1ScVal, // amount_out_min - amount_in_max
dexDistributionScValVec, // proxy_addresses: Vec<ProxyAddressPair>,
new StellarSdk.Address(address).toScVal(), //admin: Address,
StellarSdk.nativeToScVal(getCurrentTimePlusOneHour()), //deadline
];

console.log('🚀 « aggregatorSwapParams:', aggregatorSwapParams);

try {
const result = (await aggregatorCallback(
AggregatorMethod.SWAP,
aggregatorMethod,
aggregatorSwapParams,
!simulation,
)) as StellarSdk.SorobanRpc.Api.GetTransactionResponse;
Expand All @@ -168,6 +185,7 @@ export function useSwapCallback(

return { ...result, switchValues };
} catch (error) {
console.log({ error });
if (error instanceof Error) {
const parsedError = extractContractError(error.message);
throw parsedError;
Expand Down
1 change: 1 addition & 0 deletions src/services/pairs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ export const fetchAllSoroswapPairs = async (networkPassphrase: string) => {
network: networkName,
},
});

return data;
};

Expand Down
Loading

0 comments on commit 538d3a9

Please sign in to comment.