Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat/eng 439 #417

Open
wants to merge 7 commits into
base: staging
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ export function useMyVaults<T = Vault[]>({
plainVaults,
user,
)
return vaults.filter((v) => v.isActive)
return vaults?.filter((v) => v?.isActive) ?? []
} catch (error) {
console.error(error)
return []
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -156,21 +156,21 @@ export function usePostLimitOrder({ onResult }: Props = {}) {
onResult?.(receipt)
try {
// Start showing loading state indicator on parts of the UI that depend on
startLoading([TRADE.TABLES.ORDERS, TRADE.TABLES.FILLS])
startLoading([TRADE.TABLES.ORDERS, TRADE.TABLES.ORDER_HISTORY])

await resolveWhenBlockIsIndexed.mutateAsync({
blockNumber: Number(receipt.blockNumber),
})
queryClient.invalidateQueries({ queryKey: ["orders"] })
queryClient.invalidateQueries({ queryKey: ["fills"] })
queryClient.invalidateQueries({ queryKey: ["order-history"] })
queryClient.invalidateQueries({ queryKey: ["balances"] })
queryClient.invalidateQueries({ queryKey: ["mangroveTokenPrice"] })
} catch (error) {
console.error(error)
}
},
onSettled: () => {
stopLoading([TRADE.TABLES.ORDERS, TRADE.TABLES.FILLS])
stopLoading([TRADE.TABLES.ORDERS, TRADE.TABLES.ORDER_HISTORY])
},
})
}
Original file line number Diff line number Diff line change
Expand Up @@ -132,20 +132,20 @@ export function usePostMarketOrder({ onResult }: Props = {}) {
onResult?.(receipt)
try {
// Start showing loading state indicator on parts of the UI that depend on
startLoading([TRADE.TABLES.ORDERS, TRADE.TABLES.FILLS])
startLoading([TRADE.TABLES.ORDERS, TRADE.TABLES.ORDER_HISTORY])
await resolveWhenBlockIsIndexed.mutateAsync({
blockNumber: Number(receipt.blockNumber),
})
queryClient.invalidateQueries({ queryKey: ["orders"] })
queryClient.invalidateQueries({ queryKey: ["fills"] })
queryClient.invalidateQueries({ queryKey: ["order-history"] })
queryClient.invalidateQueries({ queryKey: ["balances"] })
queryClient.invalidateQueries({ queryKey: ["mangroveTokenPrice"] })
} catch (error) {
console.error(error)
}
},
onSettled: () => {
stopLoading([TRADE.TABLES.ORDERS, TRADE.TABLES.FILLS])
stopLoading([TRADE.TABLES.ORDERS, TRADE.TABLES.ORDER_HISTORY])
},
})
}
30 changes: 0 additions & 30 deletions app/trade/_components/tables/fills/schema.ts

This file was deleted.

84 changes: 0 additions & 84 deletions app/trade/_components/tables/fills/use-fills.ts

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -3,33 +3,33 @@ import React from "react"

import useMarket from "@/providers/market"
import { DataTable } from "../../../../../components/ui/data-table/data-table"
import { useFills } from "./use-fills"
import { useOrderHistory } from "./use-order-history"
import { useTable } from "./use-table"

export function Fills() {
export function OrderHistory() {
const [{ page, pageSize }, setPageDetails] = React.useState<PageDetails>({
page: 1,
pageSize: 10,
})
const { currentMarket: market } = useMarket()
const { data: count } = useFills({
select: (fills) => fills.length,
const { data: count } = useOrderHistory({
select: (orderHistory) => orderHistory.length,
})
const fillsQuery = useFills({
const orderHistoryQuery = useOrderHistory({
filters: {
skip: (page - 1) * pageSize,
},
})

const table = useTable({
data: fillsQuery.data,
data: orderHistoryQuery.data,
})

return (
<DataTable
table={table}
isError={!!fillsQuery.error}
isLoading={fillsQuery.isLoading || !market}
isError={!!orderHistoryQuery.error}
isLoading={orderHistoryQuery.isLoading || !market}
pagination={{
onPageChange: setPageDetails,
page,
Expand Down
65 changes: 65 additions & 0 deletions app/trade/_components/tables/order-history/schema.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
import { MarketParams } from "@mangrovedao/mgv"
import { z } from "zod"

export const rawOrderHistory = z.object({
side: z.string(),
type: z.string(),
received: z.number(),
sent: z.number(),
block: z.number(),
fee: z.number(),
price: z.number().nullable(),
offerId: z.string().nullable(),
status: z.string(),
transactionHash: z.string(),
lockedProvision: z.string().nullable(),
})

const marketSchema = z.object({
address: z.string(),
symbol: z.string(),
decimals: z.number(),
displayDecimals: z.number(),
})

export const orderHistorySchema = z.object({
...rawOrderHistory.shape,
market: z.object({
base: marketSchema,
quote: marketSchema,
tickSpacing: z.bigint(),
}),
})

export type OrderHistory = z.infer<typeof orderHistorySchema>

export function parseOrderHistory(
data: unknown[],
market: MarketParams,
): OrderHistory[] {
return data
.map((item) => {
try {
const rawOrder = rawOrderHistory.parse(item)

return orderHistorySchema.parse({
...rawOrder,
market: {
base: {
...market.base,
displayDecimals: market.base.displayDecimals,
},
quote: {
...market.quote,
displayDecimals: market.quote.displayDecimals,
},
tickSpacing: market.tickSpacing,
},
})
} catch (error) {
console.error("Invalid format for order history: ", item, error)
return null
}
})
.filter(Boolean) as OrderHistory[]
}
100 changes: 100 additions & 0 deletions app/trade/_components/tables/order-history/use-order-history.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
"use client"

import { useQuery } from "@tanstack/react-query"
import { useAccount } from "wagmi"

import { TRADE } from "@/app/trade/_constants/loading-keys"
import { useMgvInfra } from "@/hooks/use-mgv-infra"
import useIndexerSdk from "@/providers/mangrove-indexer"
import useMarket from "@/providers/market"
import { useLoadingStore } from "@/stores/loading.store"
import { getErrorMessage } from "@/utils/errors"
import { z } from "zod"
import { parseOrderHistory, rawOrderHistory, type OrderHistory } from "./schema"

type Params<T> = {
filters?: {
first?: number
skip?: number
}
select?: (data: OrderHistory[]) => T
}

export function useOrderHistory<T = OrderHistory[]>({
filters: { first = 100, skip = 0 } = {},
select,
}: Params<T> = {}) {
const { address, isConnected } = useAccount()
const { currentMarket, markets } = useMarket()
const { indexerSdk } = useIndexerSdk()
const { mgvInfraUrl, chainId: currentChainId } = useMgvInfra()

const [startLoading, stopLoading] = useLoadingStore((state) => [
state.startLoading,
state.stopLoading,
])
const sortedMarkets = currentMarket
? [currentMarket, ...markets.filter((m) => m !== currentMarket)]
: markets

return useQuery({
// eslint-disable-next-line @tanstack/query/exhaustive-deps
queryKey: [
"order-history",
currentMarket?.base.address,
currentMarket?.quote.address,
markets.length,
address,
first,
skip,
],
queryFn: async () => {
try {
startLoading(TRADE.TABLES.ORDER_HISTORY)
if (!(address && markets.length)) return []

const allOrders = await Promise.all(
sortedMarkets.map(async (market) => {
const response = await fetch(
`${mgvInfraUrl}/orders/history/${currentChainId}/${market.base.address}/${market.quote.address}/${market.tickSpacing}?user=${address}`,
{
headers: {
"Content-Type": "application/json",
},
},
).then(async (res) => await res.json())

const orderHistorySchema = z.object({
count: z.number(),
totalPages: z.number(),
orders: z.array(rawOrderHistory),
})

const result = orderHistorySchema.parse(response)

return result.count > 0
? parseOrderHistory(
result.orders.sort((a, b) => b.block - a.block),
market,
)
: []
}),
)
console.log(allOrders.flat())
return allOrders.flat()
} catch (e) {
console.error(getErrorMessage(e))
throw new Error()
} finally {
stopLoading(TRADE.TABLES.ORDER_HISTORY)
}
},
select,
meta: {
error: "Unable to retrieve order history",
},
enabled: !!(isConnected && indexerSdk),
retry: false,
staleTime: 1 * 60 * 1000, // 1 minute
})
}
Loading