Skip to content

Commit

Permalink
Merge pull request #572 from oraichain/fix/ODEX-122-208
Browse files Browse the repository at this point in the history
Fix/odex 122 208
  • Loading branch information
haunv3 authored Feb 2, 2024
2 parents f81684c + a6084d6 commit ede37aa
Show file tree
Hide file tree
Showing 5 changed files with 70 additions and 64 deletions.
4 changes: 3 additions & 1 deletion src/config/chainInfos.ts
Original file line number Diff line number Diff line change
Expand Up @@ -834,7 +834,8 @@ export const chainInfos: CustomChainInfo[] = [
coinDecimals: 18,
bridgeTo: ['Oraichain'],
coinGeckoId: 'ethereum',
Icon: EthIcon
Icon: EthIcon,
prefixToken: ORAI_BRIDGE_EVM_ETH_DENOM_PREFIX
},
{
coinDenom: 'USDT',
Expand Down Expand Up @@ -956,6 +957,7 @@ export const chainInfos: CustomChainInfo[] = [
coinDecimals: 18,
coinGeckoId: 'binancecoin',
bridgeTo: ['Oraichain'],
prefixToken: ORAI_BRIDGE_EVM_DENOM_PREFIX,
Icon: BnbIcon
}
]
Expand Down
3 changes: 2 additions & 1 deletion src/helper/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ export const getNetworkGasPrice = async (chainId): Promise<number> => {
if (findToken) {
return findToken.feeCurrencies[0].gasPriceStep.average;
}
} catch {}
} catch { }
return 0;
};

Expand Down Expand Up @@ -161,6 +161,7 @@ export const handleCheckAddress = async (chainId: CosmosChainId): Promise<string

const transferMsgError = (message: string, info?: InfoError) => {
if (message.includes('invalid hash')) return `Transation was not included to block`;
if (message.includes("Assertion failed; minimum receive amount")) return `Because of high demand, You can increase slippage to increase success rate of the swap!`;
if (message.includes("Cannot read properties of undefined (reading 'signed')")) return `User rejected transaction`;
if (message.includes('account sequence mismatch'))
return `Your previous transaction has not been included in a block. Please wait until it is included before creating a new transaction!`;
Expand Down
35 changes: 20 additions & 15 deletions src/hooks/useTokenFee.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@ import {
oraichainTokens,
toDisplay,
toAmount,
BigDecimal
BigDecimal,
ORAI_BRIDGE_EVM_ETH_DENOM_PREFIX,
ORAI_BRIDGE_EVM_DENOM_PREFIX
} from '@oraichain/oraidex-common';
import { OraiswapRouterQueryClient } from '@oraichain/oraidex-contracts-sdk';
import { handleSimulateSwap, isEvmNetworkNativeSwapSupported } from '@oraichain/oraidex-universal-swap';
Expand Down Expand Up @@ -34,7 +36,15 @@ export default function useTokenFee(
if (isEvmNetworkNativeSwapSupported(fromChainId) && fromChainId === toChainId) return;

const { token_fees: tokenFees } = feeConfig;
const tokenFee = tokenFees.find((tokenFee) => tokenFee.token_denom === remoteTokenDenom);
const isNativeEth = remoteTokenDenom === 'eth';
const isNativeBnb = remoteTokenDenom === 'bnb';
const tokenFee = tokenFees.find(
(tokenFee) =>
tokenFee.token_denom === remoteTokenDenom ||
// TODO
(isNativeEth && tokenFee.token_denom.includes(ORAI_BRIDGE_EVM_ETH_DENOM_PREFIX)) ||
(isNativeBnb && tokenFee.token_denom.includes(ORAI_BRIDGE_EVM_DENOM_PREFIX))
);
if (tokenFee) fee = (tokenFee.ratio.nominator / tokenFee.ratio.denominator) * 100;
setBridgeFee(fee);

Expand All @@ -47,18 +57,16 @@ export const useRelayerFeeToken = (originalFromToken: TokenItemType, originalToT
const [relayerFeeInOrai, setRelayerFeeInOrai] = useState(0);
const [relayerFee, setRelayerFeeAmount] = useState(0);
const feeConfig = useSelector((state: RootState) => state.token.feeConfigs);
const routerClient = new OraiswapRouterQueryClient(window.client, network.router);
const oraiToken = oraichainTokens.find((token) => token.coinGeckoId === 'oraichain-token');

const isWeth = originalToToken?.coinGeckoId === 'weth';
const CONSTANTS_ORAI_SIMULATE_WETH = 10;
const { data: relayerFeeAmount } = useQuery(
['simulate-relayer-data', originalFromToken, originalToToken, relayerFeeInOrai],
() => {
const routerClient = new OraiswapRouterQueryClient(window.client, network.router);
const oraiToken = oraichainTokens.find((token) => token.coinGeckoId === 'oraichain-token');
return handleSimulateSwap({
originalFromInfo: oraiToken,
originalToInfo: originalToToken,
originalAmount: isWeth ? CONSTANTS_ORAI_SIMULATE_WETH : relayerFeeInOrai,
originalAmount: relayerFeeInOrai,
routerClient
});
},
Expand All @@ -69,19 +77,16 @@ export const useRelayerFeeToken = (originalFromToken: TokenItemType, originalToT

// get relayer fee in token, by simulate orai vs to token.
useEffect(() => {
if (relayerFeeAmount)
setRelayerFeeAmount(
new BigDecimal(relayerFeeAmount.displayAmount).div(isWeth ? CONSTANTS_ORAI_SIMULATE_WETH : 1).toNumber()
);
if (relayerFeeAmount) setRelayerFeeAmount(new BigDecimal(relayerFeeAmount.displayAmount).toNumber());
}, [relayerFeeAmount]);

// get relayer fee in ORAI
useEffect(() => {
if (!originalFromToken || !originalToToken || !feeConfig) return;
const isFromChainIdEvm = EVM_CHAIN_ID.includes(originalFromToken.chainId);
const isToChainIdEvm = EVM_CHAIN_ID.includes(originalToToken.chainId);

if (isToChainIdEvm && isFromChainIdEvm === isToChainIdEvm) {
if (
isEvmNetworkNativeSwapSupported(originalFromToken.chainId) &&
originalFromToken.chainId === originalToToken.chainId
) {
setRelayerFeeAmount(0);
setRelayerFeeInOrai(0);
return;
Expand Down
48 changes: 26 additions & 22 deletions src/libs/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -161,30 +161,34 @@ export const buildUnsubscribeMessage = () => {
};

export const processWsResponseMsg = (message: any): string => {
if (message === null || message.result === null) {
return null;
}
const { result } = message;
if (
result && // 👈 null and undefined check
(Object.keys(result).length !== 0 || result.constructor !== Object)
) {
if (!result.events) return null;
const events = result.events;
const packets = events['recv_packet.packet_data'];
if (!packets) return null;
let tokens = '';
for (let packetRaw of packets) {
const packet = JSON.parse(packetRaw);
// we look for the true denom information with decimals to process
// format: {"amount":"100000000000000","denom":"oraib0xA325Ad6D9c92B55A3Fc5aD7e412B1518F96441C0","receiver":"orai...","sender":"oraib..."}
const receivedToken = cosmosTokens.find((token) => token.denom === packet.denom);
const displayAmount = toDisplay(packet.amount, receivedToken.decimals);
tokens = tokens.concat(`${displayAmount} ${receivedToken.name}, `);
try {
if (message === null || message.result === null) {
return null;
}
return tokens.substring(0, tokens.length - 2); // remove , due to concat
const { result } = message;
if (
result && // 👈 null and undefined check
(Object.keys(result).length !== 0 || result.constructor !== Object)
) {
if (!result.events) return null;
const events = result.events;
const packets = events['recv_packet.packet_data'];
if (!packets) return null;
let tokens = '';
for (let packetRaw of packets) {
const packet = JSON.parse(packetRaw);
// we look for the true denom information with decimals to process
// format: {"amount":"100000000000000","denom":"oraib0xA325Ad6D9c92B55A3Fc5aD7e412B1518F96441C0","receiver":"orai...","sender":"oraib..."}
const receivedToken = cosmosTokens.find((token) => token.denom === packet.denom);
const displayAmount = toDisplay(packet?.amount, receivedToken?.decimals);
tokens = tokens.concat(`${displayAmount} ${receivedToken?.name}, `);
}
return tokens.substring(0, tokens.length - 2); // remove , due to concat
}
return null;
} catch (error) {
console.error({ errorProcessWsResponseMsg: error });
}
return null;
};

export const generateError = (message: string) => {
Expand Down
44 changes: 19 additions & 25 deletions src/pages/UniversalSwap/SwapV3/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -132,13 +132,15 @@ const SwapComponent: React.FC<{
? tokenMap[toTokenDenom]
: getTokenOnOraichain(tokenMap[toTokenDenom].coinGeckoId) ?? tokenMap[toTokenDenom];

const remoteTokenDenomFrom = originalFromToken.contractAddress ? originalFromToken.prefix + originalFromToken.contractAddress : originalFromToken.denom;
const remoteTokenDenomTo = originalToToken.contractAddress ? originalToToken.prefix + originalToToken.contractAddress : originalToToken.denom;
const fromTokenFee = useTokenFee(
originalFromToken.prefix + originalFromToken.contractAddress,
remoteTokenDenomFrom,
fromToken.chainId,
toToken.chainId
);
const toTokenFee = useTokenFee(
originalToToken.prefix + originalToToken.contractAddress,
remoteTokenDenomTo,
fromToken.chainId,
toToken.chainId
);
Expand Down Expand Up @@ -188,19 +190,12 @@ const SwapComponent: React.FC<{

// TODO: use this constant so we can temporary simulate for all pair (specifically AIRI/USDC, ORAIX/USDC), update later after migrate contract
const isFromAiriToUsdc = originalFromToken.coinGeckoId === 'airight' && originalToToken.coinGeckoId === 'usd-coin';
const isFromOraixToUsdc = originalFromToken.coinGeckoId === 'oraidex' && originalToToken.coinGeckoId === 'usd-coin';
const isToWETH = originalToToken.coinGeckoId === 'weth';

const isFromUsdc = originalFromToken.coinGeckoId === 'usd-coin';

const INIT_SIMULATE_THOUNDSAND_AMOUNT = 1000;
const INIT_SIMULATE_TEN_AMOUNT = 10;
const INIT_AMOUNT =
isFromAiriToUsdc || isFromOraixToUsdc || isToWETH
? INIT_SIMULATE_THOUNDSAND_AMOUNT
: isFromUsdc
? INIT_SIMULATE_TEN_AMOUNT
: 1;
let INIT_AMOUNT = 1;

if (isFromAiriToUsdc) {
INIT_AMOUNT = INIT_SIMULATE_THOUNDSAND_AMOUNT;
}

const { simulateData: averageRatio } = useSimulate(
'simulate-average-data',
Expand Down Expand Up @@ -234,12 +229,12 @@ const SwapComponent: React.FC<{
const isSimulateDataDisplay = simulateData && simulateData.displayAmount;
const minimumReceive = isAverageRatio
? calculateMinReceive(
// @ts-ignore
Math.trunc(new BigDecimal(averageRatio.amount) / INIT_AMOUNT).toString(),
fromAmountTokenBalance.toString(),
userSlippage,
originalFromToken.decimals
)
// @ts-ignore
Math.trunc(new BigDecimal(averageRatio.amount) / INIT_AMOUNT).toString(),
fromAmountTokenBalance.toString(),
userSlippage,
originalFromToken.decimals
)
: '0';
const isWarningSlippage = +minimumReceive > +simulateData?.amount;
const simulateDisplayAmount = simulateData && simulateData.displayAmount ? simulateData.displayAmount : 0;
Expand All @@ -250,8 +245,8 @@ const SwapComponent: React.FC<{

const minimumReceiveDisplay = isSimulateDataDisplay
? new BigDecimal(
simulateDisplayAmount - (simulateDisplayAmount * userSlippage) / 100 - relayerFee - bridgeTokenFee
).toNumber()
simulateDisplayAmount - (simulateDisplayAmount * userSlippage) / 100 - relayerFee - bridgeTokenFee
).toNumber()
: 0;

const expectOutputDisplay = isSimulateDataDisplay
Expand Down Expand Up @@ -442,9 +437,8 @@ const SwapComponent: React.FC<{
/>

<div className={cx('ratio')}>
{`1 ${originalFromToken.name}${
averageRatio ? Number((averageRatio.displayAmount / INIT_AMOUNT).toFixed(6)) : '0'
} ${originalToToken.name}`}
{`1 ${originalFromToken.name}${averageRatio ? Number((averageRatio.displayAmount / INIT_AMOUNT).toFixed(6)) : '0'
} ${originalToToken.name}`}
</div>
</div>
</div>
Expand Down

0 comments on commit ede37aa

Please sign in to comment.