Skip to content

Commit

Permalink
Add missing types
Browse files Browse the repository at this point in the history
  • Loading branch information
adamfraser committed Nov 25, 2024
1 parent 77190e4 commit 7a622d9
Show file tree
Hide file tree
Showing 5 changed files with 67 additions and 31 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,10 @@ describe('orderbook-mid-prices-cache', () => {
describe('getMedianPrice', () => {

it('returns null when no prices are set', async () => {
const result = await getMedianPrices(client, [defaultTicker]);
const result: {[ticker: string]: string | undefined} = await getMedianPrices(
client,
[defaultTicker],
);
expect(result).toEqual({ 'BTC-USD': undefined });
});

Expand All @@ -113,7 +116,10 @@ describe('orderbook-mid-prices-cache', () => {
setPrice(defaultTicker, '50000');
setPrice(defaultTicker, '49000');

const result = await getMedianPrices(client, [defaultTicker]);
const result: {[ticker: string]: string | undefined} = await getMedianPrices(
client,
[defaultTicker],
);
expect(result).toEqual({ 'BTC-USD': '50000' });
});

Expand All @@ -123,14 +129,17 @@ describe('orderbook-mid-prices-cache', () => {
setPrice(defaultTicker, '49000');
setPrice(defaultTicker, '52000');

const result = await getMedianPrices(client, [defaultTicker]);
const result: {[ticker: string]: string | undefined} = await getMedianPrices(
client,
[defaultTicker],
);
expect(result).toEqual({ 'BTC-USD': '50500' });
});

it('returns the correct median price after 30 seconds', async () => {
jest.useFakeTimers();
// Mock the getOrderBookMidPrice function for the ticker
const mockPrices = ['50000', '51000', '49000', '48000', '52000', '53000'];
const mockPrices: string[] = ['50000', '51000', '49000', '48000', '52000', '53000'];

(OrderbookLevelsCache.getOrderBookMidPrice as jest.Mock)
.mockResolvedValueOnce(mockPrices[0])
Expand Down Expand Up @@ -160,7 +169,10 @@ describe('orderbook-mid-prices-cache', () => {
expect(OrderbookLevelsCache.getOrderBookMidPrice).toHaveBeenCalledTimes(6);

// Check the median price
const result = await getMedianPrices(client, [defaultTicker]);
const result:{[ticker: string]: string | undefined} = await getMedianPrices(
client,
[defaultTicker],
);
// Median of last 4 prices, as first two should have expired after moving clock forward
expect(result).toEqual({ 'BTC-USD': '50500' });

Expand All @@ -171,7 +183,10 @@ describe('orderbook-mid-prices-cache', () => {
setPrice(defaultTicker, '0.00000000002345');
setPrice(defaultTicker, '0.00000000002346');

const midPrice1 = await getMedianPrices(client, [defaultTicker]);
const midPrice1: { [ticker: string]: string | undefined } = await getMedianPrices(
client,
[defaultTicker],
);
expect(midPrice1).toEqual({ 'BTC-USD': '0.000000000023455' });
});

Expand All @@ -182,7 +197,10 @@ describe('orderbook-mid-prices-cache', () => {
setPrice(defaultTicker, '0.00000000004');
setPrice(defaultTicker, '0.00000000005');

const midPrice1 = await getMedianPrices(client, [defaultTicker]);
const midPrice1: { [ticker: string]: string | undefined } = await getMedianPrices(
client,
[defaultTicker],
);
expect(midPrice1).toEqual({ 'BTC-USD': '0.00000000003' });

await deleteAllAsync(client);
Expand All @@ -191,7 +209,10 @@ describe('orderbook-mid-prices-cache', () => {
setPrice(defaultTicker, '0.00000847006');
setPrice(defaultTicker, '0.00000847008');

const midPrice2 = await getMedianPrices(client, [defaultTicker]);
const midPrice2: { [ticker: string]: string | undefined } = await getMedianPrices(
client,
[defaultTicker],
);
expect(midPrice2).toEqual({ 'BTC-USD': '0.00000847007' });
});
});
Expand Down Expand Up @@ -221,7 +242,10 @@ describe('orderbook-mid-prices-cache', () => {
setPrice(solUsdTicker, '102');
setPrice(solUsdTicker, '98');

const result = await getMedianPrices(client, [btcUsdTicker, ethUsdTicker, solUsdTicker]);
const result: { [ticker: string]: string | undefined } = await getMedianPrices(
client,
[btcUsdTicker, ethUsdTicker, solUsdTicker],
);
expect(result).toEqual({
'BTC-USD': '50000',
'ETH-USD': '3000',
Expand All @@ -242,7 +266,10 @@ describe('orderbook-mid-prices-cache', () => {
setPrice(ethUsdTicker, '2900');
setPrice(ethUsdTicker, '3200');

const result = await getMedianPrices(client, [btcUsdTicker, ethUsdTicker]);
const result: { [ticker: string]: string | undefined } = await getMedianPrices(
client,
[btcUsdTicker, ethUsdTicker],
);
expect(result).toEqual({
'BTC-USD': '50500',
'ETH-USD': '3050',
Expand All @@ -263,7 +290,10 @@ describe('orderbook-mid-prices-cache', () => {

// Set no prices for SOL-USD

const result = await getMedianPrices(client, [btcUsdTicker, ethUsdTicker, solUsdTicker]);
const result: { [ticker: string]: string | undefined } = await getMedianPrices(
client,
[btcUsdTicker, ethUsdTicker, solUsdTicker],
);
expect(result).toEqual({
'BTC-USD': '50000',
'ETH-USD': '3050',
Expand All @@ -287,7 +317,10 @@ describe('orderbook-mid-prices-cache', () => {
setPrice(solUsdTicker, '0.00000125');
setPrice(solUsdTicker, '0.00000126');

const result = await getMedianPrices(client, [btcUsdTicker, ethUsdTicker, solUsdTicker]);
const result: { [ticker: string]: string | undefined } = await getMedianPrices(
client,
[btcUsdTicker, ethUsdTicker, solUsdTicker],
);
expect(result).toEqual({
'BTC-USD': '50000.123455',
'ETH-USD': '3000.6',
Expand Down
22 changes: 11 additions & 11 deletions indexer/packages/redis/src/caches/orderbook-mid-prices-cache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,10 +32,10 @@ export async function fetchAndCacheOrderbookMidPrices(
tickers: string[],
): Promise<void> {
// Fetch midPrices and filter out undefined values
const cacheKeyPricePairs = await Promise.all(
const cacheKeyPricePairs: ({ cacheKey: string, midPrice: string } | null)[] = await Promise.all(
tickers.map(async (ticker) => {
const cacheKey = getOrderbookMidPriceCacheKey(ticker);
const midPrice = await getOrderBookMidPrice(ticker, client);
const cacheKey: string = getOrderbookMidPriceCacheKey(ticker);
const midPrice: string | undefined = await getOrderBookMidPrice(ticker, client);
if (midPrice !== undefined) {
return { cacheKey, midPrice };
}
Expand All @@ -44,18 +44,18 @@ export async function fetchAndCacheOrderbookMidPrices(
);

// Filter out null values
const validPairs = cacheKeyPricePairs.filter(
const validPairs: { cacheKey: string, midPrice: string }[] = cacheKeyPricePairs.filter(
(pair): pair is { cacheKey: string, midPrice: string } => pair !== null,
);
if (validPairs.length === 0) {
// No valid midPrices to cache
return;
}

const nowSeconds = Math.floor(Date.now() / 1000); // Current time in seconds
const nowSeconds: number = Math.floor(Date.now() / 1000); // Current time in seconds
// Extract cache keys and prices
const priceValues = validPairs.map((pair) => pair.midPrice);
const priceCacheKeys = validPairs.map((pair) => {
const priceValues: string[] = validPairs.map((pair) => pair.midPrice);
const priceCacheKeys: string[] = validPairs.map((pair) => {

logger.info({
at: 'orderbook-mid-prices-cache#fetchAndCacheOrderbookMidPrices',
Expand Down Expand Up @@ -123,9 +123,9 @@ export async function getMedianPrices(
evalAsync = evalAsync.bind(client);

// Map tickers to cache keys
const marketCacheKeys = tickers.map(getOrderbookMidPriceCacheKey);
const marketCacheKeys: string[] = tickers.map(getOrderbookMidPriceCacheKey);
// Fetch the prices arrays from Redis (without scores)
const pricesArrays = await evalAsync(marketCacheKeys);
const pricesArrays: string[][] = await evalAsync(marketCacheKeys);

const result: { [ticker: string]: string | undefined } = {};
tickers.forEach((ticker, index) => {
Expand All @@ -138,13 +138,13 @@ export async function getMedianPrices(
}

// Convert the prices to Big.js objects for precision
const bigPrices = prices.map((price) => Big(price));
const bigPrices: Big[] = prices.map((price) => Big(price));

// Sort the prices in ascending order
bigPrices.sort((a, b) => a.cmp(b));

// Calculate the median
const mid = Math.floor(bigPrices.length / 2);
const mid: number = Math.floor(bigPrices.length / 2);
if (bigPrices.length % 2 === 1) {
// Odd number of prices: the middle one is the median
result[ticker] = bigPrices[mid].toFixed();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,4 @@ for i, key in ipairs(KEYS) do
results[i] = prices
end

return results
return results
Original file line number Diff line number Diff line change
Expand Up @@ -36,15 +36,15 @@ describe('cache-orderbook-mid-prices', () => {
});

it('caches mid prices for all markets', async () => {
const market1 = await PerpetualMarketTable
const market1: PerpetualMarketFromDatabase | undefined = await PerpetualMarketTable
.findByMarketId(
testConstants.defaultMarket.id,
);
const market2 = await PerpetualMarketTable
const market2: PerpetualMarketFromDatabase | undefined = await PerpetualMarketTable
.findByMarketId(
testConstants.defaultMarket2.id,
);
const market3 = await PerpetualMarketTable
const market3: PerpetualMarketFromDatabase | undefined = await PerpetualMarketTable
.findByMarketId(
testConstants.defaultMarket3.id,
);
Expand All @@ -60,7 +60,8 @@ describe('cache-orderbook-mid-prices', () => {
await runTask();
expect(OrderbookLevelsCache.getOrderBookMidPrice).toHaveBeenCalledTimes(5);

const prices = await OrderbookMidPricesCache.getMedianPrices(
const prices: {[ticker: string]: string | undefined} = await
OrderbookMidPricesCache.getMedianPrices(
redisClient,
[market1.ticker, market2.ticker, market3.ticker],
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,10 @@ import { redisClient } from '../helpers/redis';
*/
export default async function runTask(): Promise<void> {
try {
let perpetualMarkets = Object.values(perpetualMarketRefresher.getPerpetualMarketsMap());
let marketTickers = perpetualMarkets.map(
let perpetualMarkets: PerpetualMarketFromDatabase[] = Object.values(
perpetualMarketRefresher.getPerpetualMarketsMap(),
);
let marketTickers: string[] = perpetualMarkets.map(
(market: PerpetualMarketFromDatabase) => market.ticker,
);

Expand All @@ -43,7 +45,7 @@ export default async function runTask(): Promise<void> {
} catch (error) {
logger.error({
at: 'cache-orderbook-mid-prices#runTask',
message: error.message,
message: (error as Error).message,
error,
});
}
Expand Down

0 comments on commit 7a622d9

Please sign in to comment.