improve speed of updating open orders after websocket change

This commit is contained in:
tjs 2023-02-13 22:34:03 -05:00
parent fdde4baa86
commit 57f927fc15
5 changed files with 86 additions and 24 deletions

View File

@ -53,26 +53,16 @@ const HydrateStore = () => {
// watch selected Mango Account for changes // watch selected Mango Account for changes
useEffect(() => { useEffect(() => {
const client = mangoStore.getState().client const client = mangoStore.getState().client
if (!mangoAccountPk) return if (!mangoAccountPk) return
const subscriptionId = connection.onAccountChange( const subscriptionId = connection.onAccountChange(
mangoAccountPk, mangoAccountPk,
async (info, context) => { async (info, context) => {
if (info?.lamports === 0) return if (info?.lamports === 0) return
const lastSeenSlot = mangoStore.getState().mangoAccount.lastSlot const lastSeenSlot = mangoStore.getState().mangoAccount.lastSlot
// const mangoAccountLastUpdated = new Date(
// mangoStore.getState().mangoAccount.lastUpdatedAt
// )
const mangoAccount = mangoStore.getState().mangoAccount.current const mangoAccount = mangoStore.getState().mangoAccount.current
if (!mangoAccount) return if (!mangoAccount) return
// const newUpdatedAt = new Date()
// const timeDiff =
// mangoAccountLastUpdated.getTime() - newUpdatedAt.getTime()
// only updated mango account if it's been more than 1 second since last update
// if (Math.abs(timeDiff) >= 500 && context.slot > lastSeenSlot) {
if (context.slot > lastSeenSlot) { if (context.slot > lastSeenSlot) {
const decodedMangoAccount = client.program.coder.accounts.decode( const decodedMangoAccount = client.program.coder.accounts.decode(
'mangoAccount', 'mangoAccount',
@ -83,10 +73,8 @@ const HydrateStore = () => {
decodedMangoAccount decodedMangoAccount
) )
await newMangoAccount.reloadSerum3OpenOrders(client) await newMangoAccount.reloadSerum3OpenOrders(client)
actions.fetchOpenOrders() actions.fetchOpenOrders(newMangoAccount)
// newMangoAccount.spotOpenOrdersAccounts =
// mangoAccount.spotOpenOrdersAccounts
// newMangoAccount.advancedOrders = mangoAccount.advancedOrders
set((s) => { set((s) => {
s.mangoAccount.current = newMangoAccount s.mangoAccount.current = newMangoAccount
s.mangoAccount.lastSlot = context.slot s.mangoAccount.lastSlot = context.slot

View File

@ -20,7 +20,6 @@ import { Table, Td, Th, TrBody, TrHead } from './TableElements'
import useSelectedMarket from 'hooks/useSelectedMarket' import useSelectedMarket from 'hooks/useSelectedMarket'
import ConnectEmptyState from './ConnectEmptyState' import ConnectEmptyState from './ConnectEmptyState'
import { useWallet } from '@solana/wallet-adapter-react' import { useWallet } from '@solana/wallet-adapter-react'
import Decimal from 'decimal.js'
import FormatNumericValue from './FormatNumericValue' import FormatNumericValue from './FormatNumericValue'
import BankAmountWithValue from './BankAmountWithValue' import BankAmountWithValue from './BankAmountWithValue'
import useBanksWithBalances, { import useBanksWithBalances, {
@ -290,7 +289,6 @@ const Balance = ({ bank }: { bank: BankWithBalance }) => {
} }
}, [tokenBank, selectedMarket]) }, [tokenBank, selectedMarket])
console.log(tokenBank.name, ' balance', new Decimal(balance).toFixed())
if (!balance) return <p className="flex justify-end">0</p> if (!balance) return <p className="flex justify-end">0</p>
return ( return (

View File

@ -164,8 +164,6 @@ const fetchJupiterTransaction = async (
const filtered_jup_ixs = ixs const filtered_jup_ixs = ixs
.filter((ix) => !isSetupIx(ix.programId)) .filter((ix) => !isSetupIx(ix.programId))
.filter((ix) => !isDuplicateAta(ix)) .filter((ix) => !isDuplicateAta(ix))
console.log('ixs: ', ixs)
console.log('filtered ixs: ', filtered_jup_ixs)
return [filtered_jup_ixs, alts] return [filtered_jup_ixs, alts]
} }

View File

@ -1,13 +1,15 @@
import ExplorerLink from '@components/shared/ExplorerLink' import ExplorerLink from '@components/shared/ExplorerLink'
import useMangoGroup from 'hooks/useMangoGroup' import useMangoGroup from 'hooks/useMangoGroup'
import type { NextPage } from 'next' import type { NextPage } from 'next'
import { ReactNode } from 'react' import { ReactNode, useCallback, useEffect, useState } from 'react'
import { serverSideTranslations } from 'next-i18next/serverSideTranslations' import { serverSideTranslations } from 'next-i18next/serverSideTranslations'
import useMangoAccount from 'hooks/useMangoAccount' import useMangoAccount from 'hooks/useMangoAccount'
import { import {
toUiDecimalsForQuote, toUiDecimalsForQuote,
HealthType, HealthType,
PerpOrder,
} from '@blockworks-foundation/mango-v4' } from '@blockworks-foundation/mango-v4'
import mangoStore from '@store/mangoStore'
export async function getStaticProps({ locale }: { locale: string }) { export async function getStaticProps({ locale }: { locale: string }) {
return { return {
@ -22,6 +24,29 @@ const Dashboard: NextPage = () => {
// const { mangoTokens } = useJupiterMints() // const { mangoTokens } = useJupiterMints()
// const client = mangoStore(s => s.client) // const client = mangoStore(s => s.client)
const { mangoAccount } = useMangoAccount() const { mangoAccount } = useMangoAccount()
const client = mangoStore((s) => s.client)
const [openOrders, setOpenOrders] = useState<Record<string, PerpOrder[]>>()
useEffect(() => {
if (mangoAccount) {
loadOpenOrders()
}
}, [mangoAccount])
const loadOpenOrders = useCallback(async () => {
if (!mangoAccount || !group) return
const openOrders: Record<string, any> = {}
for (const perpOrder of mangoAccount.perpOrdersActive()) {
const market = group.getPerpMarketByMarketIndex(perpOrder.orderMarket)
const orders = await mangoAccount.loadPerpOpenOrdersForMarket(
client,
group,
perpOrder.orderMarket
)
openOrders[market.publicKey.toString()] = orders
}
setOpenOrders(openOrders)
}, [mangoAccount, client, group])
return ( return (
<div className="grid grid-cols-12"> <div className="grid grid-cols-12">
@ -222,6 +247,49 @@ const Dashboard: NextPage = () => {
</div> </div>
) )
})} })}
<h3 className="mt-4">Perp Open Orders</h3>
{openOrders
? Object.entries(openOrders).map(
([marketAddress, openOrders]) => {
return (
<div key={marketAddress} className="mt-4">
<KeyValuePair
label="Market Address"
value={<ExplorerLink address={marketAddress} />}
/>
{openOrders.map((openOrder) => {
return (
<div
key={`${openOrder.orderId}${openOrder.side}${openOrder.seqNum}`}
className="mt-4 rounded border border-th-bkg-3 px-2"
>
<KeyValuePair
label="Side"
value={
openOrder.side
? 'bid' in openOrder.side
? 'Bid'
: 'Ask'
: null
}
/>
<KeyValuePair
label="Price"
value={openOrder.price}
/>
<KeyValuePair
label="Size"
value={openOrder.size}
/>
</div>
)
})}
</div>
)
}
)
: null}
</div> </div>
) : ( ) : (
'Loading' 'Loading'

View File

@ -95,6 +95,8 @@ const initMangoClient = (
}) })
} }
let mangoGroupRetryAttempt = 0
export interface TotalInterestDataItem { export interface TotalInterestDataItem {
borrow_interest: number borrow_interest: number
deposit_interest: number deposit_interest: number
@ -603,7 +605,7 @@ const mangoStore = create<MangoStore>()(
state.activityFeed.feed = combinedFeed state.activityFeed.feed = combinedFeed
}) })
} catch (e) { } catch (e) {
console.log('Failed to fetch account activity feed', e) console.error('Failed to fetch account activity feed', e)
} finally { } finally {
set((state) => { set((state) => {
state.activityFeed.loading = false state.activityFeed.loading = false
@ -656,9 +658,15 @@ const mangoStore = create<MangoStore>()(
) )
} }
}) })
mangoGroupRetryAttempt = 0
} catch (e) { } catch (e) {
notify({ type: 'info', title: 'Unable to refresh data' }) if (mangoGroupRetryAttempt < 2) {
console.error('Error fetching group', e) // get().actions.fetchGroup()
mangoGroupRetryAttempt++
} else {
notify({ type: 'info', title: 'Unable to refresh data' })
console.error('Error fetching group', e)
}
} }
}, },
reloadMangoAccount: async () => { reloadMangoAccount: async () => {
@ -813,8 +821,10 @@ const mangoStore = create<MangoStore>()(
mangoAccount.serum3Active().length && mangoAccount.serum3Active().length &&
Object.keys(openOrders).length Object.keys(openOrders).length
) { ) {
serumOpenOrderAccounts = serumOpenOrderAccounts = Array.from(
await mangoAccount.loadSerum3OpenOrdersAccounts(client) mangoAccount.serum3OosMapByMarketIndex.values()
)
await mangoAccount.loadSerum3OpenOrdersAccounts(client)
} }
for (const perpOrder of mangoAccount.perpOrdersActive()) { for (const perpOrder of mangoAccount.perpOrdersActive()) {