Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Summary
Native price is being used in several places of the app. Mostly for limit orders to get the market price, and for getting USD price.
I saw that, on load the native price for some tokens was being fetched at least 6 times.
BEFORE:
AFTER:
Context
One of the reasons we fetch so many times, is because we fetch it for multiple markets, and there's some repetition in the tokens of the markets. It does 1 call per token.
One easy way to fix, its to provide a cached version of the
getNativePrice
inapps/cowswap-frontend/src/api/cowProtocol/api.ts
Normally we add caching either:
One problem with these approaches, is that
api
is not a hook. They are pure functions.In this case, If we wanted to use caching using hooks it would be more complicated, because we need to get an instance of the fetch function in other hooks or components and pass it. Native price is being used in multiple place, so it seems too complicated.
Quick LRU
I added a convenient library to add a simple and lightweight LRU cache (
3.2K
)Generic caching tool
I implemented a generic
fetchWithCache
which makes use of quick LRU caches.This utility, will cache promises and not the resolved object. With this, we can make sure the native price is only fetched once. If we cached the resolved object, it would fetch 6 times on load for the same token, because the app would try to fetch in parallel the same token multiple times, and the result would not be in the cache.
Caching the response allow us to only fetch it once per TTL interval.
Next PRS
One thing I would like to do, is to use this solution as just a temporary one, and implement all the refreshing logics in the SDK. I have some ideas, but its completely out of the scope of this PR.