Skip to content

Commit

Permalink
fix(usd-amount): debounce deletion currency from USD price queue
Browse files Browse the repository at this point in the history
  • Loading branch information
shoom3301 committed Sep 7, 2023
1 parent f87b8d2 commit 75367c7
Showing 1 changed file with 27 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ import { atom } from 'jotai'

import { Fraction, Token } from '@uniswap/sdk-core'

import ms from 'ms.macro'

import { deepEqual } from 'utils/deepEqual'

export interface UsdRawPriceState {
Expand All @@ -13,14 +15,21 @@ export interface UsdRawPriceState {

export type UsdRawPrices = { [tokenAddress: string]: UsdRawPriceState }

const DELETION_FROM_QUEUE_DEBOUNCE = ms`5s`

export const currenciesUsdPriceQueueAtom = atom<{ [tokenAddress: string]: Token }>({})

export const usdRawPricesAtom = atom<UsdRawPrices>({})

const currenciesToDeleteFromQueueAtom = atom<{ [tokenAddress: string]: Token | undefined }>({})

export const addCurrencyToUsdPriceQueue = atom(null, (get, set, currency: Token) => {
const currencyAddress = currency.address.toLowerCase()
const currenciesToLoadUsdPrice = get(currenciesUsdPriceQueueAtom)

// Remove the currency from deletion queue
set(currenciesToDeleteFromQueueAtom, { ...get(currenciesToDeleteFromQueueAtom), [currencyAddress]: undefined })

if (!currenciesToLoadUsdPrice[currencyAddress]) {
set(currenciesUsdPriceQueueAtom, {
...currenciesToLoadUsdPrice,
Expand All @@ -32,12 +41,26 @@ export const addCurrencyToUsdPriceQueue = atom(null, (get, set, currency: Token)
export const removeCurrencyToUsdPriceFromQueue = atom(null, (get, set, currency: Token) => {
const currencyAddress = currency.address.toLowerCase()
const currenciesToLoadUsdPrice = get(currenciesUsdPriceQueueAtom)
const currenciesToDeleteFromQueue = get(currenciesToDeleteFromQueueAtom)

const isCurrencyInUsdPriceQueue = !!currenciesToLoadUsdPrice[currencyAddress]
const isCurrencyInDeletionQueue = !!currenciesToDeleteFromQueue[currencyAddress]

if (isCurrencyInUsdPriceQueue && !isCurrencyInDeletionQueue) {
// Add the currency from deletion queue
set(currenciesToDeleteFromQueueAtom, { ...currenciesToDeleteFromQueue, [currencyAddress]: currency })

setTimeout(() => {
const state = { ...get(currenciesUsdPriceQueueAtom) }

if (currenciesToLoadUsdPrice[currencyAddress]) {
const stateCopy = { ...currenciesToLoadUsdPrice }
delete stateCopy[currencyAddress]
// Remove the currency from USD price queue only if it's not added again
if (get(currenciesToDeleteFromQueueAtom)[currencyAddress]) {
set(currenciesToDeleteFromQueueAtom, { ...get(currenciesToDeleteFromQueueAtom), [currencyAddress]: undefined })
delete state[currencyAddress]

set(currenciesUsdPriceQueueAtom, stateCopy)
set(currenciesUsdPriceQueueAtom, state)
}
}, DELETION_FROM_QUEUE_DEBOUNCE)
}
})

Expand Down

0 comments on commit 75367c7

Please sign in to comment.