Skip to content

Commit

Permalink
feat: add estimateLoading for open/close position
Browse files Browse the repository at this point in the history
  • Loading branch information
naturexie committed Jan 15, 2025
1 parent 2da219d commit efb5f67
Show file tree
Hide file tree
Showing 9 changed files with 123 additions and 106 deletions.
40 changes: 39 additions & 1 deletion api/get-pool.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import { ViewMethodsDcl, ChangeMethodsDcl } from "../interfaces/index";
import { fetchAllPools, getStablePools } from "@ref-finance/ref-sdk";
import { ViewMethodsDcl, ViewMethodsREFV1 } from "../interfaces/index";
import { getBurrow } from "../utils";
import { IPoolDcl, IQuoteResult, IPool } from "../interfaces/pool";
import getConfig from "../utils/config";
import { expandToken } from "../store/helper";

export async function getDclPools() {
const { view, dclContract } = await getBurrow();
Expand Down Expand Up @@ -53,3 +55,39 @@ export async function get_pool_list(poolType: "classic" | "stable" | "degen" | "
});
return data?.data?.list || [];
}
async function get_stable_pool_details(pool_ids: string[]) {
const { view, refv1Contract } = await getBurrow();
const allStablePools: IPoolDcl[] = (await view(
refv1Contract,
ViewMethodsREFV1[ViewMethodsREFV1.get_pool_detail_info_by_ids],
{
pool_ids,
},
)) as IPoolDcl[];
const poolKindMap = {
RatedPoolInfo: "RATED_SWAP",
StablePoolInfo: "STABLE_SWAP",
DegenPoolInfo: "DEGEN_SWAP",
};
const stablePools = allStablePools.map((poolDetail, index) => {
const [key, pool_info] = Object.entries(poolDetail)[0] as any[];
return {
...pool_info,
pool_kind: poolKindMap[key],
id: pool_ids[index],
rates: pool_info.rates || pool_info.c_amounts.map(() => expandToken(1, 18)),
};
});
return stablePools;
}
export async function get_pools_from_sdk() {
const { ratedPools, unRatedPools, simplePools } = await fetchAllPools();
const stablePools = unRatedPools.concat(ratedPools);
const pool_ids = stablePools.map((p) => p.id);
const stablePoolsDetail = await get_stable_pool_details(pool_ids);
return {
simplePools,
stablePools,
stablePoolsDetail,
};
}
4 changes: 3 additions & 1 deletion components/Header/WalletButton.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -379,10 +379,12 @@ export const ConnectWalletButton = ({
accountId,
className,
isShort,
loading,
}: {
accountId;
className?: string;
isShort?: boolean;
loading?: boolean;
}) => {
const [isDisclaimerOpen, setDisclaimer] = useState(false);
const { getDisclaimer: hasAgreedDisclaimer } = useDisclaimer();
Expand Down Expand Up @@ -422,7 +424,7 @@ export const ConnectWalletButton = ({
onClick={onWalletButtonClick}
disableRipple={!!accountId}
>
Connect Wallet
{loading ? <BeatLoader size={4} color="black" /> : <>Connect Wallet</>}
</Button>
<Disclaimer isOpen={isDisclaimerOpen} onClose={() => setDisclaimer(false)} />
</>
Expand Down
9 changes: 8 additions & 1 deletion hooks/useDclEstimateSwap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ export const useDclEstimateSwap = ({
forceUpdate?: number;
}) => {
const [estimateData, setEstimateData] = useState<IEstimateResult>();
const [loading, setLoading] = useState<boolean>(false);
const combinedAssetsData = useAppSelector(getAllAssetsData);
const allDclPools = useAppSelector(getDclPools);
useEffect(() => {
Expand Down Expand Up @@ -72,6 +73,7 @@ export const useDclEstimateSwap = ({
tag: `${pool_id}@${expandAmount}`,
}),
);
setLoading(true);
const estimatesResult = await Promise.allSettled(quotePending);
const fulfilledEstimates = estimatesResult.filter((res) => res.status == "fulfilled");
const estimates = fulfilledEstimates.map((r) => r.value);
Expand All @@ -89,6 +91,7 @@ export const useDclEstimateSwap = ({
tag: `${tokenIn_id}@${tokenOut_id}@${tokenIn_amount}`,
from: "dcl",
});
setLoading(false);
return;
}
const dexMap = get_registered_dexes();
Expand Down Expand Up @@ -120,6 +123,10 @@ export const useDclEstimateSwap = ({
tag: `${tokenIn_id}@${tokenOut_id}@${tokenIn_amount}`,
from: "dcl",
});
setLoading(false);
}
return estimateData;
return {
estimateData,
loading,
};
};
24 changes: 11 additions & 13 deletions hooks/useEstimateSwap.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { useEffect, useState } from "react";
import Decimal from "decimal.js";
import { init_env } from "@ref-finance/ref-sdk";
import { useV1EstimateSwap } from "./useV1EstimateSwap";
import { useDclEstimateSwap } from "./useDclEstimateSwap";
import { IEstimateResult } from "../interfaces";
Expand All @@ -11,43 +10,36 @@ export const useEstimateSwap = ({
tokenIn_amount,
slippageTolerance,
account_id,
simplePools,
stablePools,
stablePoolsDetail,
forceUpdate,
}: {
tokenIn_id: string;
tokenOut_id: string;
tokenIn_amount: string;
slippageTolerance: number;
account_id?: string;
simplePools: any[];
stablePools: any[];
stablePoolsDetail: any[];
forceUpdate?: number;
}) => {
const [estimateResult, setEstimateResult] = useState<IEstimateResult>();
const dclEstimateResult: any = useDclEstimateSwap({
const [estimateLoading, setEstimateLoading] = useState<boolean>(false);
const { estimateData: dclEstimateResult, loading: dclLoading }: any = useDclEstimateSwap({
tokenIn_id,
tokenOut_id,
tokenIn_amount,
slippageTolerance,
forceUpdate,
});
const v1EstimateResult: any = useV1EstimateSwap({
const { estimateData: v1EstimateResult, loading: v1Loading }: any = useV1EstimateSwap({
tokenIn_id,
tokenOut_id,
tokenIn_amount,
slippageTolerance,
account_id,
simplePools,
stablePools,
stablePoolsDetail,
forceUpdate,
});
useEffect(() => {
if (dclEstimateResult?.tag && v1EstimateResult?.tag && validator()) {
getBestEstimateResult();
setEstimateLoading(false);
}
if (tokenIn_amount == "0" || !tokenIn_amount) {
setEstimateResult((prev: any) => {
Expand All @@ -64,6 +56,9 @@ export const useEstimateSwap = ({
v1EstimateResult?.amount_out,
tokenIn_amount,
]);
useEffect(() => {
setEstimateLoading(v1Loading || dclLoading);
}, [v1Loading, dclLoading]);
function getBestEstimateResult() {
const { amount_out: dcl_amount_out } = dclEstimateResult!;
const { amount_out: v1_amount_out } = v1EstimateResult!;
Expand Down Expand Up @@ -93,5 +88,8 @@ export const useEstimateSwap = ({
}
return false;
}
return estimateResult;
return {
estimateResult,
estimateLoading,
};
};
15 changes: 5 additions & 10 deletions hooks/useGetPoolsData.ts
Original file line number Diff line number Diff line change
@@ -1,25 +1,20 @@
import { useState, useEffect } from "react";
import { fetchAllPools, getStablePools, init_env } from "@ref-finance/ref-sdk";
import { get_pools_from_sdk } from "../api/get-pool";

export function usePoolsData() {
const [simplePools, setSimplePools] = useState<any[]>([]);
const [stablePools, setStablePools] = useState<any[]>([]);
const [stablePoolsDetail, setStablePoolsDetail] = useState<any[]>([]);

useEffect(() => {
getPoolsData();
}, []);

async function getPoolsData() {
try {
//
const { ratedPools, unRatedPools, simplePools: simplePoolsFromSdk } = await fetchAllPools();
const stablePoolsFromSdk = unRatedPools.concat(ratedPools);
const stablePoolsDetailFromSdk = await getStablePools(stablePoolsFromSdk);

setSimplePools(simplePoolsFromSdk);
setStablePools(stablePoolsFromSdk);
setStablePoolsDetail(stablePoolsDetailFromSdk);
const { simplePools, stablePools, stablePoolsDetail } = await get_pools_from_sdk();
setSimplePools(simplePools);
setStablePools(stablePools);
setStablePoolsDetail(stablePoolsDetail);
} catch (error) {
console.error("Error fetching pools data:", error);
}
Expand Down
52 changes: 25 additions & 27 deletions hooks/useV1EstimateSwap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import {
getExpectedOutputFromSwapTodos,
instantSwap,
Transaction,
init_env,
getAvgFee,
} from "@ref-finance/ref-sdk";
import { isEmpty } from "lodash";
Expand All @@ -23,33 +22,32 @@ import {
get_amount_from_msg,
get_registered_dexes,
} from "../utils/margin";
import { get_pools_from_sdk } from "../api/get-pool";

const SHUTDOWN_SERVER = false;
let simplePools;
let stablePools;
let stablePoolsDetail;
export const useV1EstimateSwap = ({
tokenIn_id,
tokenOut_id,
tokenIn_amount,
slippageTolerance,
account_id,
simplePools,
stablePools,
stablePoolsDetail,
forceUpdate,
}: {
tokenIn_id: string;
tokenOut_id: string;
tokenIn_amount: string;
slippageTolerance: number;
account_id?: string;
simplePools: any[];
stablePools: any[];
stablePoolsDetail: any[];
forceUpdate?: number;
}) => {
const combinedAssetsData = useAppSelector(getAllAssetsData);
const marginConfig = useAppSelector(getMarginConfig);
const allPools = useAppSelector(getAllPools);
const [estimateData, setEstimateData] = useState<IEstimateResult>();
const [loading, setLoading] = useState<boolean>(false);
const [tokenIn_metadata, tokenOut_metadata] = useMemo(() => {
if (tokenIn_id && tokenOut_id) {
const [tokenIn_metadata, tokenOut_metadata] = getMetadatas([
Expand All @@ -61,27 +59,12 @@ export const useV1EstimateSwap = ({
return [];
}, [tokenIn_id, tokenOut_id]);
useEffect(() => {
if (
!isEmpty(combinedAssetsData) &&
!isEmpty(simplePools) &&
!isEmpty(stablePools) &&
!isEmpty(stablePoolsDetail) &&
Number(tokenIn_amount) > 0
) {
if (!isEmpty(combinedAssetsData) && Number(tokenIn_amount) > 0) {
getEstimateSwapData();
}
}, [
combinedAssetsData,
tokenIn_id,
tokenOut_id,
tokenIn_amount,
slippageTolerance,
simplePools?.length,
stablePools?.length,
stablePoolsDetail?.length,
forceUpdate,
]);
}, [combinedAssetsData, tokenIn_id, tokenOut_id, tokenIn_amount, slippageTolerance, forceUpdate]);
async function getEstimateSwapData() {
setLoading(true);
if (SHUTDOWN_SERVER) {
getEstimateSwapFromScript();
} else {
Expand All @@ -95,7 +78,11 @@ export const useV1EstimateSwap = ({
tokenIn: tokenIn_id,
tokenOut: tokenOut_id,
slippage: slippageTolerance,
}).catch(() => ({}));
})
.catch(() => ({}))
.finally(() => {
setLoading(false);
});
if (!(resultFromServer?.result_code !== 0 || !resultFromServer?.result_data?.routes?.length)) {
const result: IFindPathResult = resultFromServer.result_data;
let min_output_amount = new Decimal(0);
Expand Down Expand Up @@ -138,6 +125,12 @@ export const useV1EstimateSwap = ({
}
}
async function getEstimateSwapFromScript() {
if (!simplePools) {
const poolsMap = await get_pools_from_sdk();
simplePools = poolsMap.simplePools;
stablePools = poolsMap.stablePools;
stablePoolsDetail = poolsMap.stablePoolsDetail;
}
const [tokenIn_metadata, tokenOut_metadata] = getMetadatas([
combinedAssetsData[tokenIn_id],
combinedAssetsData[tokenOut_id],
Expand Down Expand Up @@ -173,6 +166,8 @@ export const useV1EstimateSwap = ({
slippageTolerance,
AccountId: account_id || "test_account_id",
referralId: "app.burrow.finance",
}).finally(() => {
setLoading(false);
});
const swapTransaction = transactionsRef.pop() as any;
const [dex_id, msg] = get_swap_indication_info(swapTransaction, marginConfig.registered_dexes);
Expand Down Expand Up @@ -247,5 +242,8 @@ export const useV1EstimateSwap = ({
});
return avgFee;
}
return estimateData;
return {
estimateData,
loading,
};
};
1 change: 1 addition & 0 deletions interfaces/contract-methods.ts
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,7 @@ export enum ViewMethodsREFV1 {
get_shadow_records,
get_pool_volumes_by_ids,
list_pool_volumes,
get_pool_detail_info_by_ids,
}
export enum ChangeMethodsREFV1 {
shadow_action,
Expand Down
15 changes: 2 additions & 13 deletions screens/Trading/components/ClosePositionMobile.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,7 @@ import { toInternationalCurrencySystem_number, toDecimal } from "../../../utils/
import { closePosition } from "../../../store/marginActions/closePosition";
import { useEstimateSwap } from "../../../hooks/useEstimateSwap";
import { useAccountId } from "../../../hooks/hooks";
import { usePoolsData } from "../../../hooks/useGetPoolsData";
import {
expandToken,
shrinkToken,
shrinkTokenDecimal,
expandTokenDecimal,
} from "../../../store/helper";
import { expandToken, shrinkToken, shrinkTokenDecimal } from "../../../store/helper";
import {
YellowSolidSubmitButton as YellowSolidButton,
RedSolidSubmitButton as RedSolidButton,
Expand Down Expand Up @@ -73,8 +67,6 @@ const ClosePositionMobile: React.FC<IClosePositionMobileProps> = ({
(state) => state.category,
);
const accountId = useAccountId();
const { simplePools, stablePools, stablePoolsDetail } = usePoolsData();

const assetD = getAssetById(item.token_d_info.token_id, item);
const assetC = getAssetById(item.token_c_info.token_id, item);
const assetP = getAssetById(item.token_p_id, item);
Expand Down Expand Up @@ -114,14 +106,11 @@ const ClosePositionMobile: React.FC<IClosePositionMobileProps> = ({
}, [positionType.label]);

// estimate
const estimateData = useEstimateSwap({
const { estimateResult: estimateData } = useEstimateSwap({
tokenIn_id: item.token_p_id,
tokenOut_id: item.token_d_info.token_id,
tokenIn_amount: shrinkToken(tokenInAmount || "0", assetP.metadata.decimals),
account_id: accountId,
simplePools,
stablePools,
stablePoolsDetail,
slippageTolerance: ReduxSlippageTolerance / 100,
forceUpdate,
});
Expand Down
Loading

0 comments on commit efb5f67

Please sign in to comment.