Implement dynamic routes + price impact

This commit is contained in:
Bob van der Helm 2024-01-24 18:26:44 +01:00
parent 7cfe05ebb7
commit 8e2e16e286
No known key found for this signature in database
GPG Key ID: 59FC90B476A8CB39
9 changed files with 409 additions and 416 deletions

View File

@ -13,13 +13,12 @@ import { DEFAULT_SETTINGS } from 'constants/defaultSettings'
import { LocalStorageKeys } from 'constants/localStorageKeys'
import useAllAssets from 'hooks/assets/useAllAssets'
import useLocalStorage from 'hooks/localStorage/useLocalStorage'
import useRouteInfo from 'hooks/trade/useRouteInfo'
import useLiquidationPrice from 'hooks/useLiquidationPrice'
import usePrice from 'hooks/usePrice'
import useSwapFee from 'hooks/useSwapFee'
import useToggle from 'hooks/useToggle'
import { BNCoin } from 'types/classes/BNCoin'
import { byDenom } from 'utils/array'
import { formatAmountWithSymbol, formatPercent } from 'utils/formatters'
import { formatAmountWithSymbol, formatPercent, formatValue } from 'utils/formatters'
interface Props {
borrowAmount: BigNumber
@ -32,7 +31,6 @@ interface Props {
estimatedFee: StdFee
isMargin?: boolean
liquidationPrice: number | null
route: Route[]
sellAmount: BigNumber
sellAsset: Asset
showProgressIndicator: boolean
@ -52,7 +50,6 @@ export default function TradeSummary(props: Props) {
borrowAmount,
estimatedFee,
showProgressIndicator,
route,
sellAmount,
buyAmount,
isAdvanced,
@ -61,34 +58,24 @@ export default function TradeSummary(props: Props) {
const [slippage] = useLocalStorage<number>(LocalStorageKeys.SLIPPAGE, DEFAULT_SETTINGS.slippage)
const assets = useAllAssets()
const sellAssetPrice = usePrice(sellAsset.denom)
// FIXME: ⛓️ Swap fee needs to be chainagnostic!
const swapFee = useSwapFee(route.map((route) => route.pool_id))
const [showSummary, setShowSummary] = useToggle()
const { liquidationPrice, isUpdatingLiquidationPrice } = useLiquidationPrice(
props.liquidationPrice,
)
const { data: routeInfo } = useRouteInfo(sellAsset.denom, buyAsset.denom, sellAmount)
const minReceive = useMemo(() => {
return buyAmount.times(1 - swapFee).times(1 - slippage)
}, [buyAmount, slippage, swapFee])
return buyAmount.times(1 - (routeInfo?.fee.toNumber() || 0)).times(1 - slippage)
}, [buyAmount, routeInfo?.fee, slippage])
const swapFeeValue = useMemo(() => {
return sellAssetPrice.times(swapFee).times(sellAmount)
}, [sellAmount, sellAssetPrice, swapFee])
const parsedRoutes = useMemo(() => {
if (!route.length) return '-'
const routeSymbols = route.map((r) => assets.find(byDenom(r.token_out_denom))?.symbol)
routeSymbols.unshift(sellAsset.symbol)
return routeSymbols.join(' -> ')
}, [assets, route, sellAsset.symbol])
return sellAmount.times(routeInfo?.fee || 0).times(sellAssetPrice)
}, [routeInfo?.fee, sellAmount, sellAssetPrice])
const buttonText = useMemo(() => {
if (!isAdvanced && direction === 'short') return `Sell ${sellAsset.symbol}`
return route.length ? `Buy ${buyAsset.symbol}` : 'No route found'
}, [buyAsset.symbol, route, sellAsset.symbol, isAdvanced, direction])
return `Buy ${buyAsset.symbol}`
}, [isAdvanced, direction, sellAsset.symbol, buyAsset.symbol])
return (
<div
@ -155,7 +142,26 @@ export default function TradeSummary(props: Props) {
</div>
{showSummary && (
<>
<SummaryLine label={`Swap fees (${(swapFee || 0.002) * 100}%)`} className='mt-2'>
<SummaryLine label='Price impact' className='mt-2'>
{routeInfo?.priceImpact ? (
<FormattedNumber
amount={routeInfo?.priceImpact.times(100).toNumber() || 0}
options={{ suffix: '%' }}
/>
) : (
'-'
)}
</SummaryLine>
<SummaryLine
label={`Swap fees ${
routeInfo?.fee
? formatValue(routeInfo.fee.times(100).decimalPlaces(2).toNumber(), {
prefix: '(',
suffix: '%)',
})
: ''
}`}
>
<DisplayCurrency coin={BNCoin.fromDenomAndBigNumber(sellAsset.denom, swapFeeValue)} />
</SummaryLine>
<SummaryLine label='Transaction fees'>
@ -172,7 +178,7 @@ export default function TradeSummary(props: Props) {
/>
</SummaryLine>
<Divider className='my-2' />
<SummaryLine label='Route'>{parsedRoutes}</SummaryLine>
<SummaryLine label='Route'>{routeInfo?.description}</SummaryLine>
</>
)}
</div>

View File

@ -24,10 +24,10 @@ import useMarketEnabledAssets from 'hooks/assets/useMarketEnabledAssets'
import useLocalStorage from 'hooks/localStorage/useLocalStorage'
import useMarketAssets from 'hooks/markets/useMarketAssets'
import useMarketBorrowings from 'hooks/markets/useMarketBorrowings'
import useRouteInfo from 'hooks/trade/useRouteInfo'
import useAutoLend from 'hooks/useAutoLend'
import useChainConfig from 'hooks/useChainConfig'
import useHealthComputer from 'hooks/useHealthComputer'
import useSwapRoute from 'hooks/useSwapRoute'
import useToggle from 'hooks/useToggle'
import { useUpdatedAccount } from 'hooks/useUpdatedAccount'
import useStore from 'store'
@ -61,10 +61,6 @@ export default function SwapForm(props: Props) {
if (tradeDirection === 'long') return [sellAsset, buyAsset]
return [buyAsset, sellAsset]
}, [buyAsset, sellAsset, tradeDirection, isAdvanced])
const { data: route, isLoading: isRouteLoading } = useSwapRoute(
inputAsset.denom,
outputAsset.denom,
)
const isBorrowEnabled = !!marketAssets.find(byDenom(inputAsset.denom))?.borrowEnabled
const isRepayable = !!account?.debts.find(byDenom(outputAsset.denom))
const [isMarginChecked, setMarginChecked] = useToggle(isBorrowEnabled ? useMargin : false)
@ -85,6 +81,7 @@ export default function SwapForm(props: Props) {
const { computeLiquidationPrice } = useHealthComputer(updatedAccount)
const chainConfig = useChainConfig()
const assets = useMarketEnabledAssets()
const { data: routeInfo } = useRouteInfo(sellAsset.denom, buyAsset.denom, inputAssetAmount)
const depositCapReachedCoins: BNCoin[] = useMemo(() => {
const outputMarketAsset = marketAssets.find(byDenom(outputAsset.denom))
@ -165,6 +162,8 @@ export default function SwapForm(props: Props) {
}, [marginRatio, maxOutputAmountEstimation])
const swapTx = useMemo(() => {
if (!routeInfo) return
const borrowCoin = inputAssetAmount.isGreaterThan(imputMarginThreshold)
? BNCoin.fromDenomAndBigNumber(inputAsset.denom, inputAssetAmount.minus(imputMarginThreshold))
: undefined
@ -178,16 +177,18 @@ export default function SwapForm(props: Props) {
slippage,
isMax: inputAssetAmount.isEqualTo(maxInputAmount),
repay: isAutoRepayChecked,
route: routeInfo.route,
})
}, [
removedLends,
account?.id,
outputAsset.denom,
routeInfo,
inputAssetAmount,
imputMarginThreshold,
inputAsset.denom,
inputAssetAmount,
slippage,
swap,
account?.id,
removedLends,
outputAsset.denom,
slippage,
maxInputAmount,
isAutoRepayChecked,
])
@ -227,14 +228,14 @@ export default function SwapForm(props: Props) {
)
useEffect(() => {
swapTx.estimateFee().then(setEstimatedFee)
swapTx?.estimateFee().then(setEstimatedFee)
}, [swapTx])
const handleBuyClick = useCallback(async () => {
if (account?.id) {
setIsConfirming(true)
const isSucceeded = await swapTx.execute()
const isSucceeded = await swapTx?.execute()
if (isSucceeded) {
setInputAssetAmount(BN_ZERO)
@ -332,9 +333,8 @@ export default function SwapForm(props: Props) {
() =>
inputAssetAmount.isZero() ||
depositCapReachedCoins.length > 0 ||
borrowAmount.isGreaterThan(availableLiquidity) ||
route.length === 0,
[inputAssetAmount, depositCapReachedCoins, borrowAmount, availableLiquidity, route],
borrowAmount.isGreaterThan(availableLiquidity),
[inputAssetAmount, depositCapReachedCoins, borrowAmount, availableLiquidity],
)
return (
@ -453,11 +453,10 @@ export default function SwapForm(props: Props) {
borrowRate={borrowAsset?.borrowRate}
buyAction={handleBuyClick}
buyButtonDisabled={isSwapDisabled}
showProgressIndicator={isConfirming || isRouteLoading}
showProgressIndicator={isConfirming}
isMargin={isMarginChecked}
borrowAmount={borrowAmount}
estimatedFee={estimatedFee}
route={route}
liquidationPrice={liquidationPrice}
sellAmount={inputAssetAmount}
buyAmount={outputAssetAmount}

View File

@ -1,16 +1,21 @@
import useSWR from 'swr'
import useAllAssets from 'hooks/assets/useAllAssets'
import useChainConfig from 'hooks/useChainConfig'
import useDebounce from 'hooks/useDebounce'
import { ChainInfoID } from 'types/enums/wallet'
import { byDenom } from 'utils/array'
import { BN } from 'utils/helpers'
export default function useRoutes(denomIn: string, denomOut: string, amount: BigNumber) {
export default function useRouteInfo(denomIn: string, denomOut: string, amount: BigNumber) {
const chainConfig = useChainConfig()
const isOsmosis = [ChainInfoID.Osmosis1, ChainInfoID.OsmosisDevnet].includes(chainConfig.id)
const assets = useAllAssets()
const debouncedAmount = useDebounce<string>(amount.toString(), 500)
const osmosisRoute = useSWR<SwapRouteInfo | null>(
isOsmosis &&
`${chainConfig.endpoints.routes}/quote?tokenIn=${denomIn}&tokenOutDenom=${denomOut}&amount=${amount}`,
`${chainConfig.endpoints.routes}/quote?tokenIn=${debouncedAmount}${denomIn}&tokenOutDenom=${denomOut}`,
async (url: string) => {
try {
const resp = await fetch(url)
@ -19,15 +24,24 @@ export default function useRoutes(denomIn: string, denomOut: string, amount: Big
return {
priceImpact: BN(route.price_impact),
fee: BN(route.effective_fee),
description: [
assets.find(byDenom(denomIn))?.symbol,
...route.route[0].pools.map(
(pool) => assets.find(byDenom(pool.token_out_denom))?.symbol,
),
].join(' -> '),
route: {
osmo: {
swaps: route.route[0].pools.map((pool) => ({
swaps: route.route[0].pools.map(
(pool) =>
({
pool_id: pool.id.toString(),
to: pool.token_out_denom,
})),
}) as unknown,
),
},
},
}
} as SwapRouteInfo
} catch {
return null
}
@ -36,7 +50,7 @@ export default function useRoutes(denomIn: string, denomOut: string, amount: Big
const astroportRoute = useSWR<SwapRouteInfo | null>(
!isOsmosis &&
`${chainConfig.endpoints.routes}?start=${denomIn}&end=${denomOut}&amount=${amount}&chainId=${chainConfig.id}&limit=1`,
`${chainConfig.endpoints.routes}?start=${denomIn}&end=${denomOut}&amount=${debouncedAmount}&chainId=${chainConfig.id}&limit=1`,
async (url: string) => {
try {
const resp = await fetch(url)
@ -45,6 +59,10 @@ export default function useRoutes(denomIn: string, denomOut: string, amount: Big
return {
priceImpact: BN(route.price_impact),
fee: BN(0), // TODO: Fees are not implemented yet on Astroport endpoint
description: [
assets.find(byDenom(denomIn))?.symbol,
...route.swaps.map((swap) => assets.find(byDenom(swap.to))?.symbol),
].join(' -> '),
route: {
astro: {
swaps: route.swaps.map((swap) => ({

View File

@ -1,23 +0,0 @@
import useSWR from 'swr'
import getOsmosisSwapFee from 'api/swap/getOsmosisSwapFee'
import useChainConfig from 'hooks/useChainConfig'
import { ChainInfoID } from 'types/enums/wallet'
import { STANDARD_SWAP_FEE } from 'utils/constants'
export default function useSwapFee(poolIds: string[]) {
const chainConfig = useChainConfig()
const { data: swapFee } = useSWR(
`chains/${chainConfig.id}/swapFees/${poolIds.join(',')}`,
() => {
if (chainConfig.id === ChainInfoID.Pion1) {
return STANDARD_SWAP_FEE
}
return getOsmosisSwapFee(chainConfig, poolIds)
},
{},
)
return swapFee ?? STANDARD_SWAP_FEE
}

View File

@ -1,16 +0,0 @@
import useSWR from 'swr'
import getSwapRoute from 'api/swap/getSwapRoute'
import useChainConfig from 'hooks/useChainConfig'
export default function useSwapRoute(denomIn: string, denomOut: string) {
const chainConfig = useChainConfig()
return useSWR(
`swapRoute-${denomIn}-${denomOut}`,
() => getSwapRoute(chainConfig, denomIn, denomOut),
{
fallbackData: [],
revalidateOnFocus: false,
},
)
}

View File

@ -15,6 +15,7 @@ import {
Action as CreditManagerAction,
ExecuteMsg as CreditManagerExecuteMsg,
ExecuteMsg,
SwapperRoute,
} from 'types/generated/mars-credit-manager/MarsCreditManager.types'
import { AccountKind } from 'types/generated/mars-rover-health-types/MarsRoverHealthTypes.types'
import { byDenom, bySymbol } from 'utils/array'
@ -764,6 +765,7 @@ export default function createBroadcastSlice(
slippage: number
isMax?: boolean
repay: boolean
route: SwapperRoute
}) => {
const msg: CreditManagerExecuteMsg = {
update_credit_account: {
@ -776,6 +778,7 @@ export default function createBroadcastSlice(
coin_in: options.coinIn.toActionCoin(options.isMax),
denom_out: options.denomOut,
slippage: options.slippage.toString(),
route: options.route as SwapperRoute,
},
},
...(options.repay

View File

@ -130,6 +130,7 @@ export type Action =
swap_exact_in: {
coin_in: ActionCoin
denom_out: string
route?: SwapperRoute | null
slippage: Decimal
}
}
@ -168,8 +169,14 @@ export type LiquidateRequestForVaultBaseForString =
}
}
export type VaultPositionType = 'u_n_l_o_c_k_e_d' | 'l_o_c_k_e_d' | 'u_n_l_o_c_k_i_n_g'
export type SwapperRoute =
| {
astro: AstroRoute
}
| {
osmo: OsmoRoute
}
export type AccountNftBaseForString = string
export type PerpsBaseForString = string
export type OwnerUpdate =
| {
propose_new_owner: {
@ -323,6 +330,7 @@ export type CallbackMsg =
account_id: string
coin_in: ActionCoin
denom_out: string
route?: SwapperRoute | null
slippage: Decimal
}
}
@ -414,6 +422,20 @@ export interface SignedDecimal {
export interface VaultBaseForString {
address: string
}
export interface AstroRoute {
swaps: AstroSwap[]
}
export interface AstroSwap {
from: string
to: string
}
export interface OsmoRoute {
swaps: OsmoSwap[]
}
export interface OsmoSwap {
pool_id: number
to: string
}
export interface ConfigUpdates {
account_nft?: AccountNftBaseForString | null
health_contract?: HealthContractBaseForString | null

View File

@ -42,25 +42,8 @@ type OsmosisRoutePool = {
type SwapRouteInfo = {
priceImpact: BigNumber
fee: BigNumber
route: OsmosisSwap | AstroportSwap
}
type OsmosisSwap = {
osmo: {
swaps: {
pool_id: string
to: string
}[]
}
}
type AstroportSwap = {
astro: {
swaps: {
from: string
to: string
}[]
}
route: import('types/generated/mars-credit-manager/MarsCreditManager.types').SwapperRoute
description: string
}
type AstroportRouteResponse = {

View File

@ -141,6 +141,7 @@ interface BroadcastSlice {
slippage: number
isMax?: boolean
repay: boolean
route: import('types/generated/mars-credit-manager/MarsCreditManager.types').SwapperRoute
}) => ExecutableTx
toast: ToastResponse | ToastPending | null
unlock: (options: {