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
useEffect(() => {
const client = mangoStore.getState().client
if (!mangoAccountPk) return
const subscriptionId = connection.onAccountChange(
mangoAccountPk,
async (info, context) => {
if (info?.lamports === 0) return
const lastSeenSlot = mangoStore.getState().mangoAccount.lastSlot
// const mangoAccountLastUpdated = new Date(
// mangoStore.getState().mangoAccount.lastUpdatedAt
// )
const mangoAccount = mangoStore.getState().mangoAccount.current
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) {
const decodedMangoAccount = client.program.coder.accounts.decode(
'mangoAccount',
@ -83,10 +73,8 @@ const HydrateStore = () => {
decodedMangoAccount
)
await newMangoAccount.reloadSerum3OpenOrders(client)
actions.fetchOpenOrders()
// newMangoAccount.spotOpenOrdersAccounts =
// mangoAccount.spotOpenOrdersAccounts
// newMangoAccount.advancedOrders = mangoAccount.advancedOrders
actions.fetchOpenOrders(newMangoAccount)
set((s) => {
s.mangoAccount.current = newMangoAccount
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 ConnectEmptyState from './ConnectEmptyState'
import { useWallet } from '@solana/wallet-adapter-react'
import Decimal from 'decimal.js'
import FormatNumericValue from './FormatNumericValue'
import BankAmountWithValue from './BankAmountWithValue'
import useBanksWithBalances, {
@ -290,7 +289,6 @@ const Balance = ({ bank }: { bank: BankWithBalance }) => {
}
}, [tokenBank, selectedMarket])
console.log(tokenBank.name, ' balance', new Decimal(balance).toFixed())
if (!balance) return <p className="flex justify-end">0</p>
return (

View File

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

View File

@ -1,13 +1,15 @@
import ExplorerLink from '@components/shared/ExplorerLink'
import useMangoGroup from 'hooks/useMangoGroup'
import type { NextPage } from 'next'
import { ReactNode } from 'react'
import { ReactNode, useCallback, useEffect, useState } from 'react'
import { serverSideTranslations } from 'next-i18next/serverSideTranslations'
import useMangoAccount from 'hooks/useMangoAccount'
import {
toUiDecimalsForQuote,
HealthType,
PerpOrder,
} from '@blockworks-foundation/mango-v4'
import mangoStore from '@store/mangoStore'
export async function getStaticProps({ locale }: { locale: string }) {
return {
@ -22,6 +24,29 @@ const Dashboard: NextPage = () => {
// const { mangoTokens } = useJupiterMints()
// const client = mangoStore(s => s.client)
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 (
<div className="grid grid-cols-12">
@ -222,6 +247,49 @@ const Dashboard: NextPage = () => {
</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>
) : (
'Loading'

View File

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