From ba71c46decddb526d9f7630d6955b245d6479c92 Mon Sep 17 00:00:00 2001 From: Nick Adamson Date: Thu, 11 Jan 2024 10:20:08 -0800 Subject: [PATCH] =?UTF-8?q?=F0=9F=90=9B=20(Spot):=20update=20`useSpotPrice?= =?UTF-8?q?`=20to=20use=20new=20proto?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/hooks/useSpotPrice.ts | 50 +++++++++++++++++++-------------------- 1 file changed, 24 insertions(+), 26 deletions(-) diff --git a/src/hooks/useSpotPrice.ts b/src/hooks/useSpotPrice.ts index 989db49..8238d5a 100644 --- a/src/hooks/useSpotPrice.ts +++ b/src/hooks/useSpotPrice.ts @@ -1,4 +1,4 @@ -import { useMemo } from 'react'; +import { useMemo, useState } from 'react'; import type { Address } from 'viem'; import type { UseQueryResult } from '@tanstack/react-query'; import { useChainId } from 'wagmi'; @@ -100,8 +100,15 @@ export function useSpotPrice({ return new SpotPriceRequest({ spotPriceInfo }); }, [chainId, spotPriceRequest]); + const [spotPrices, setSpotPrices] = useState< + Record + >({ + WETH: undefined, + USDC: undefined, + }); + const service = createQueryService({ service: Spot }); - const { data, ...rest } = useStream( + const { data: _data, ...rest } = useStream( { ...Spot.methods.getSpotPrice, service: { @@ -112,33 +119,24 @@ export function useSpotPrice({ request, { enabled, + onResponse(response) { + const { tokenAddress, spotPrice } = response; + const price = spotPrice !== undefined ? fromH256(spotPrice) : undefined; + const address = + tokenAddress !== undefined + ? fromH160ToAddress(tokenAddress) + : undefined; + + if (price && address) { + const symbol = addressToSymbolMap.get(address); + if (symbol) { + setSpotPrices((prev) => ({ ...prev, [symbol]: price })); + } + } + }, }, ); - const spotPrices = useMemo(() => { - if (data?.responses === undefined) return undefined; - const prices: Record = {}; - const latestResponse = data.responses[0]; - - latestResponse.spotPriceInfo.forEach((info) => { - const { tokenAddress, spotPrice } = info; - const price = spotPrice !== undefined ? fromH256(spotPrice) : undefined; - const address = - tokenAddress !== undefined - ? fromH160ToAddress(tokenAddress) - : undefined; - - if (price && address) { - const symbol = addressToSymbolMap.get(address); - if (symbol) { - prices[symbol] = price; - } - } - }); - - return prices; - }, [addressToSymbolMap, data?.responses]); - return { spotPrices, ...(rest as Omit<