vega-frontend-monorepo/apps/trading/hooks/use-orders.ts

146 lines
3.2 KiB
TypeScript
Raw Normal View History

Feat/84 Order list (#89) * scaffold dealticket package, remove trading views from react-helpers * add deal ticket component, add intent utils, expand dialog and form group styles * add splash component, show market not found message if market doesnt exist * tidy up error handling * add handleError method for vega tx hook * add better testname for provider test, flesh out tests a bit more for deal ticket * Add unit tests for useVegaTransaction and useOrderSubmit hooks * add wrapper component for order dialog styles * add vega styled loader to ui toolkit and use in order dialog * add title prop to order dialog * add button radio component * revert dialog styles * move splash component to ui-toolkit, add story * convert intent to enum * add date-fns, add datetime to helpers * add order types to wallet package, make price undefined if order type is market * tidy up order state by moving submit and transaction hooks out of deal ticket * add types package, delete old generated types from trading project * rename types package to graphql * add order list container and order list component * add test setup for useOrders * add test for use-orders hook * tidy unnecessary diff * regen types and use them in order-list, also change to use applytransaction hook for orderlist grid * make order table columns resizable * make market table not have highlightable cells, use splash for orders errors and loading states, unit test for orderlist container * add tests for order list table * show rejection reason and expires at depending on status and tif * add decimal places to query * only update row if data has changed, add test coverage * add setup tests file to avoid importing jest-dom for every test, add async-renderer component to handle fetch ui logic * install all of lodash but import individually to get tree shaking * add setup tests file for orderlist package * add missing fields to use orders spec mock order * fix act warnings in index page test * fix casing of app import * remove react-singleton-hook, simplify side formatting * fix linting errors
2022-03-23 19:08:10 +00:00
import { gql, useApolloClient } from '@apollo/client';
import { useCallback, useEffect, useState } from 'react';
import {
OrderSub,
OrderSubVariables,
Orders,
OrdersVariables,
OrderFields,
} from '@vegaprotocol/graphql';
import uniqBy from 'lodash/uniqBy';
import orderBy from 'lodash/orderBy';
import { useVegaWallet } from '@vegaprotocol/wallet';
const ORDER_FRAGMENT = gql`
fragment OrderFields on Order {
id
market {
id
name
decimalPlaces
tradableInstrument {
instrument {
code
}
}
}
type
side
size
status
rejectionReason
price
timeInForce
remaining
expiresAt
createdAt
updatedAt
}
`;
export const ORDERS_QUERY = gql`
${ORDER_FRAGMENT}
query Orders($partyId: ID!) {
party(id: $partyId) {
id
orders {
...OrderFields
}
}
}
`;
export const ORDERS_SUB = gql`
${ORDER_FRAGMENT}
subscription OrderSub($partyId: ID!) {
orders(partyId: $partyId) {
...OrderFields
}
}
`;
interface UseOrders {
orders: OrderFields[];
error: Error | null;
loading: boolean;
}
export const useOrders = (): UseOrders => {
const client = useApolloClient();
const { keypair } = useVegaWallet();
const [orders, setOrders] = useState<OrderFields[]>([]);
const [error, setError] = useState<Error | null>(null);
const [loading, setLoading] = useState(false);
const mergeOrders = useCallback((update: OrderFields[]) => {
// A subscription payload can contain multiple updates for a single order so we need to first
// sort them by updatedAt (or createdAt if the order hasn't been updated) with the newest first,
// then use uniqBy, which selects the first occuring order for an id to ensure we only get the latest order
setOrders((curr) => {
const sorted = orderBy(
[...curr, ...update],
(o) => {
if (!o.updatedAt) return new Date(o.createdAt).getTime();
return new Date(o.updatedAt).getTime();
},
'desc'
);
const uniq = uniqBy(sorted, 'id');
return uniq;
});
}, []);
// Make initial fetch
useEffect(() => {
const fetchOrders = async () => {
if (!keypair?.pub) return;
setLoading(true);
try {
const res = await client.query<Orders, OrdersVariables>({
query: ORDERS_QUERY,
variables: { partyId: keypair.pub },
});
if (!res.data.party?.orders?.length) return;
Feat/84 Order list (#89) * scaffold dealticket package, remove trading views from react-helpers * add deal ticket component, add intent utils, expand dialog and form group styles * add splash component, show market not found message if market doesnt exist * tidy up error handling * add handleError method for vega tx hook * add better testname for provider test, flesh out tests a bit more for deal ticket * Add unit tests for useVegaTransaction and useOrderSubmit hooks * add wrapper component for order dialog styles * add vega styled loader to ui toolkit and use in order dialog * add title prop to order dialog * add button radio component * revert dialog styles * move splash component to ui-toolkit, add story * convert intent to enum * add date-fns, add datetime to helpers * add order types to wallet package, make price undefined if order type is market * tidy up order state by moving submit and transaction hooks out of deal ticket * add types package, delete old generated types from trading project * rename types package to graphql * add order list container and order list component * add test setup for useOrders * add test for use-orders hook * tidy unnecessary diff * regen types and use them in order-list, also change to use applytransaction hook for orderlist grid * make order table columns resizable * make market table not have highlightable cells, use splash for orders errors and loading states, unit test for orderlist container * add tests for order list table * show rejection reason and expires at depending on status and tif * add decimal places to query * only update row if data has changed, add test coverage * add setup tests file to avoid importing jest-dom for every test, add async-renderer component to handle fetch ui logic * install all of lodash but import individually to get tree shaking * add setup tests file for orderlist package * add missing fields to use orders spec mock order * fix act warnings in index page test * fix casing of app import * remove react-singleton-hook, simplify side formatting * fix linting errors
2022-03-23 19:08:10 +00:00
mergeOrders(res.data.party.orders);
} catch (err) {
setError(
err instanceof Error ? err : new Error('Something went wrong')
);
Feat/84 Order list (#89) * scaffold dealticket package, remove trading views from react-helpers * add deal ticket component, add intent utils, expand dialog and form group styles * add splash component, show market not found message if market doesnt exist * tidy up error handling * add handleError method for vega tx hook * add better testname for provider test, flesh out tests a bit more for deal ticket * Add unit tests for useVegaTransaction and useOrderSubmit hooks * add wrapper component for order dialog styles * add vega styled loader to ui toolkit and use in order dialog * add title prop to order dialog * add button radio component * revert dialog styles * move splash component to ui-toolkit, add story * convert intent to enum * add date-fns, add datetime to helpers * add order types to wallet package, make price undefined if order type is market * tidy up order state by moving submit and transaction hooks out of deal ticket * add types package, delete old generated types from trading project * rename types package to graphql * add order list container and order list component * add test setup for useOrders * add test for use-orders hook * tidy unnecessary diff * regen types and use them in order-list, also change to use applytransaction hook for orderlist grid * make order table columns resizable * make market table not have highlightable cells, use splash for orders errors and loading states, unit test for orderlist container * add tests for order list table * show rejection reason and expires at depending on status and tif * add decimal places to query * only update row if data has changed, add test coverage * add setup tests file to avoid importing jest-dom for every test, add async-renderer component to handle fetch ui logic * install all of lodash but import individually to get tree shaking * add setup tests file for orderlist package * add missing fields to use orders spec mock order * fix act warnings in index page test * fix casing of app import * remove react-singleton-hook, simplify side formatting * fix linting errors
2022-03-23 19:08:10 +00:00
} finally {
setLoading(false);
}
};
fetchOrders();
}, [mergeOrders, keypair, client]);
// Start subscription
useEffect(() => {
if (!keypair?.pub) return;
const sub = client
.subscribe<OrderSub, OrderSubVariables>({
query: ORDERS_SUB,
variables: { partyId: keypair.pub },
})
.subscribe(({ data }) => {
if (!data?.orders) {
return;
}
Feat/84 Order list (#89) * scaffold dealticket package, remove trading views from react-helpers * add deal ticket component, add intent utils, expand dialog and form group styles * add splash component, show market not found message if market doesnt exist * tidy up error handling * add handleError method for vega tx hook * add better testname for provider test, flesh out tests a bit more for deal ticket * Add unit tests for useVegaTransaction and useOrderSubmit hooks * add wrapper component for order dialog styles * add vega styled loader to ui toolkit and use in order dialog * add title prop to order dialog * add button radio component * revert dialog styles * move splash component to ui-toolkit, add story * convert intent to enum * add date-fns, add datetime to helpers * add order types to wallet package, make price undefined if order type is market * tidy up order state by moving submit and transaction hooks out of deal ticket * add types package, delete old generated types from trading project * rename types package to graphql * add order list container and order list component * add test setup for useOrders * add test for use-orders hook * tidy unnecessary diff * regen types and use them in order-list, also change to use applytransaction hook for orderlist grid * make order table columns resizable * make market table not have highlightable cells, use splash for orders errors and loading states, unit test for orderlist container * add tests for order list table * show rejection reason and expires at depending on status and tif * add decimal places to query * only update row if data has changed, add test coverage * add setup tests file to avoid importing jest-dom for every test, add async-renderer component to handle fetch ui logic * install all of lodash but import individually to get tree shaking * add setup tests file for orderlist package * add missing fields to use orders spec mock order * fix act warnings in index page test * fix casing of app import * remove react-singleton-hook, simplify side formatting * fix linting errors
2022-03-23 19:08:10 +00:00
mergeOrders(data.orders);
});
return () => {
if (sub) {
sub.unsubscribe();
}
};
}, [client, keypair, mergeOrders]);
return { orders, error, loading };
};