Skip to content

Commit

Permalink
fix(limit-orders): do not override user entered price (#5232)
Browse files Browse the repository at this point in the history
  • Loading branch information
shoom3301 authored Dec 19, 2024
1 parent 159f6ac commit a07740c
Showing 1 changed file with 15 additions and 14 deletions.
Original file line number Diff line number Diff line change
@@ -1,37 +1,37 @@
import { useSetAtom } from 'jotai'
import { useLayoutEffect, useState } from 'react'
import { useAtomValue, useSetAtom } from 'jotai'
import { useEffect, useLayoutEffect, useState } from 'react'

import { usePrevious } from '@cowprotocol/common-hooks'

import { Writeable } from 'types'

import { useGetInitialPrice } from 'modules/limitOrders/hooks/useGetInitialPrice'
import { useUpdateActiveRate } from 'modules/limitOrders/hooks/useUpdateActiveRate'
import { LimitRateState, updateLimitRateAtom } from 'modules/limitOrders/state/limitRateAtom'

import { useLimitOrdersDerivedState } from '../../hooks/useLimitOrdersDerivedState'
import { useGetInitialPrice } from '../../hooks/useGetInitialPrice'
import { useLimitOrdersRawState } from '../../hooks/useLimitOrdersRawState'
import { useUpdateActiveRate } from '../../hooks/useUpdateActiveRate'
import { limitRateAtom, LimitRateState, updateLimitRateAtom } from '../../state/limitRateAtom'

// Fetch and update initial price for the selected token pair
export function InitialPriceUpdater() {
const { inputCurrency, outputCurrency } = useLimitOrdersDerivedState()
const { inputCurrencyId, outputCurrencyId } = useLimitOrdersRawState()
const { isTypedValue } = useAtomValue(limitRateAtom)
const updateLimitRateState = useSetAtom(updateLimitRateAtom)
const updateRate = useUpdateActiveRate()

const [isInitialPriceSet, setIsInitialPriceSet] = useState(false)
const [isInitialPriceSet, setIsInitialPriceSet] = useState(isTypedValue)
const { price, isLoading } = useGetInitialPrice()
const prevPrice = usePrevious(price)

useEffect(() => {
setIsInitialPriceSet(isTypedValue)
}, [isTypedValue])

useLayoutEffect(() => {
const update: Partial<Writeable<LimitRateState>> = {
initialRate: price,
// Don't change isLoading flag when price is already set
isLoading: isInitialPriceSet ? false : isLoading,
}

if (!isInitialPriceSet) {
update.isTypedValue = false
}

updateLimitRateState(update)
}, [isInitialPriceSet, price, isLoading, updateLimitRateState])

Expand All @@ -40,6 +40,7 @@ export function InitialPriceUpdater() {
if (!price || isInitialPriceSet || isLoading || prevPrice?.equalTo(price)) return

setIsInitialPriceSet(true)

updateRate({
activeRate: price,
isInitialPriceSet: true,
Expand All @@ -53,7 +54,7 @@ export function InitialPriceUpdater() {
// Reset initial price set flag when any token was changed
useLayoutEffect(() => {
setIsInitialPriceSet(false)
}, [inputCurrency, outputCurrency])
}, [inputCurrencyId, outputCurrencyId])

return null
}

0 comments on commit a07740c

Please sign in to comment.