Skip to content
This repository has been archived by the owner on Oct 1, 2024. It is now read-only.

Commit

Permalink
Merge pull request #45 from metaDAOproject/feature/ws-fetching-with-f…
Browse files Browse the repository at this point in the history
…allback

Feature/ws fetching with fallback
  • Loading branch information
R-K-H authored Mar 8, 2024
2 parents d0f2575 + 7e2ffff commit 15bc268
Show file tree
Hide file tree
Showing 17 changed files with 707 additions and 689 deletions.
44 changes: 36 additions & 8 deletions components/Markets/ConditionalMarketCard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,10 @@ import { useProposal } from '@/contexts/ProposalContext';
import { useExplorerConfiguration } from '@/hooks/useExplorerConfiguration';
import MarketTitle from './MarketTitle';
import DisableNumberInputScroll from '../Utilities/DisableNumberInputScroll';
import { useBalance } from '../../hooks/useBalance';
import { useProvider } from '@/hooks/useProvider';
import { useProposalMarkets } from '@/contexts/ProposalMarketsContext';
import { useBalances } from '@/contexts/BalancesContext';
import { useBalance } from '@/hooks/useBalance';

type Props = {
asks: any[][];
Expand All @@ -48,6 +49,7 @@ export function ConditionalMarketCard({
const { daoState } = useAutocrat();
const { proposal, isCranking, crankMarkets } = useProposal();
const { orderBookObject, markets, placeOrder } = useProposalMarkets();
const { setBalanceByMint } = useBalances();
const provider = useProvider();
const [orderType, setOrderType] = useState<string>('Limit');
const [orderSide, setOrderSide] = useState<string>('Buy');
Expand Down Expand Up @@ -200,13 +202,15 @@ export function ConditionalMarketCard({

const maxOrderAmount = () => {
if (isAskSide) {
if (Number(baseBalance?.uiAmountString || 0) > 0) {
return Number(baseBalance?.uiAmountString || 0);
if (Number(baseBalance?.data?.uiAmountString || 0) > 0) {
return Number(baseBalance?.data?.uiAmountString || 0);
}
return 0;
}
if (quoteBalance && price) {
const _maxAmountRatio = Math.floor(Number(quoteBalance?.uiAmountString) / Number(price));
const _maxAmountRatio = Math.floor(
Number(quoteBalance?.data?.uiAmountString) / Number(price),
);
return _maxAmountRatio;
}
return 0;
Expand Down Expand Up @@ -268,7 +272,30 @@ export function ConditionalMarketCard({
const handlePlaceOrder = useCallback(async () => {
try {
setIsPlacingOrder(true);
await placeOrder(amount, _orderPrice(), isLimitOrder, isAskSide, isPassMarket);
const txsSent = await placeOrder(
amount,
_orderPrice(),
isLimitOrder,
isAskSide,
isPassMarket,
);
if (txsSent && txsSent.length > 0) {
const marketAccount = isPassMarket
? { account: markets.pass, publicKey: proposal?.account.openbookPassMarket }
: { account: markets.fail, publicKey: proposal?.account.openbookFailMarket };
const relevantMint = isAskSide
? marketAccount.account.baseMint
: marketAccount.account.quoteMint;
setBalanceByMint(relevantMint, (oldBalance) => {
const newAmount = (oldBalance.uiAmount ?? 0) - amount;
return {
...oldBalance,
amount: newAmount.toString(),
uiAmount: newAmount,
uiAmountString: newAmount.toString(),
};
});
}
} finally {
setIsPlacingOrder(false);
}
Expand Down Expand Up @@ -554,16 +581,17 @@ export function ConditionalMarketCard({
</Grid.Col>
</Grid>
<Group align="center" justify="space-between">
{baseBalance?.uiAmountString || quoteBalance?.uiAmountString ? (
{baseBalance?.data?.uiAmountString || quoteBalance?.data?.uiAmountString ? (
<Group gap={0}>
<IconWallet height={12} />
<Text size="xs">
{isAskSide
? `${isPassMarket ? 'p' : 'f'}META ${
numeral(baseBalance?.uiAmountString || 0).format(BASE_FORMAT) || ''
numeral(baseBalance?.data?.uiAmountString || 0).format(BASE_FORMAT) || ''
}`
: `${isPassMarket ? 'p' : 'f'}USDC $${
numeral(quoteBalance?.uiAmountString || 0).format(NUMERAL_FORMAT) || ''
numeral(quoteBalance?.data?.uiAmountString || 0).format(NUMERAL_FORMAT) ||
''
}`}
</Text>
</Group>
Expand Down
27 changes: 10 additions & 17 deletions components/OrderBook/OrderConfigurationCard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -54,13 +54,9 @@ export function OrderConfigurationCard({
const base = _marketInstrument[0];
const quote = _marketInstrument[1];

const { amount: baseBalance } = useBalance(
market.market.baseMint
);
const { amount: baseBalance } = useBalance(market.market.baseMint);

const { amount: quoteBalance } = useBalance(
market.market.quoteMint
);
const { amount: quoteBalance } = useBalance(market.market.quoteMint);

const _orderPrice = () => {
if (isLimitOrder) {
Expand Down Expand Up @@ -167,12 +163,7 @@ export function OrderConfigurationCard({
if (!openbookMarket) return;
try {
setIsPlacingOrder(true);
await openbookMarket.placeOrder(
amount,
_orderPrice(),
isLimitOrder,
isAskSide
);
await openbookMarket.placeOrder(amount, _orderPrice(), isLimitOrder, isAskSide);
} catch (err) {
// TODO: Stub for app reporting
} finally {
Expand Down Expand Up @@ -281,15 +272,17 @@ export function OrderConfigurationCard({
</Grid.Col>
</Grid>
<Group align="center" justify="space-between">
{baseBalance?.uiAmountString || quoteBalance?.uiAmountString ? (
{baseBalance?.data?.uiAmountString || quoteBalance?.data?.uiAmountString ? (
<Group gap={0}>
<IconWallet height={12} />
<Text size="xs">
{isAskSide
? `${base} ${numeral(baseBalance?.uiAmountString || 0).format(BASE_FORMAT) || ''
}`
: `${quote} ${numeral(quoteBalance?.uiAmountString || 0).format(NUMERAL_FORMAT) || ''
}`}
? `${base} ${
numeral(baseBalance?.data?.uiAmountString || 0).format(BASE_FORMAT) || ''
}`
: `${quote} ${
numeral(quoteBalance?.data?.uiAmountString || 0).format(NUMERAL_FORMAT) || ''
}`}
</Text>
</Group>
) : (
Expand Down
119 changes: 68 additions & 51 deletions components/Orders/ProposalOpenOrderRow.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,18 +27,21 @@ import { NUMERAL_FORMAT, BASE_FORMAT, QUOTE_LOTS } from '@/lib/constants';
import { useProposal } from '@/contexts/ProposalContext';
import { isBid, isPartiallyFilled, isPass } from '@/lib/openbook';
import { useProposalMarkets } from '@/contexts/ProposalMarketsContext';
// import { useBalances } from '@/contexts/BalancesContext';
import { useBalances } from '@/contexts/BalancesContext';

export function ProposalOpenOrderRow({ order }: { order: OpenOrdersAccountWithKey; }) {
export function ProposalOpenOrderRow({ order }: { order: OpenOrdersAccountWithKey }) {
const theme = useMantineTheme();
const sender = useTransactionSender();
const wallet = useWallet();
const { generateExplorerLink } = useExplorerConfiguration();
const { proposal } = useProposal();
const { markets, fetchOpenOrders, cancelAndSettleOrder } = useProposalMarkets();
const { settleFundsTransactions, editOrderTransactions } =
useOpenbookTwap();
// const { fetchBalance } = useBalances();
const { settleFundsTransactions, editOrderTransactions } = useOpenbookTwap();
const { setBalanceByMint } = useBalances();
const isBidSide = isBid(order);
const balance = isBidSide
? order.account.position.bidsBaseLots
: order.account.position.asksBaseLots;

const [isCanceling, setIsCanceling] = useState<boolean>(false);
const [isEditing, setIsEditing] = useState<boolean>(false);
Expand All @@ -56,49 +59,50 @@ export function ProposalOpenOrderRow({ order }: { order: OpenOrdersAccountWithKe

try {
setIsCanceling(true);
await cancelAndSettleOrder(order, marketAccount.publicKey);
// TODO: Commenting out so we have a reference point for the future
// which will allow for failover for WS issues or account issues.
// await fetchBalance(marketAccount.account.baseMint);
// await fetchBalance(marketAccount.account.quoteMint);
const txsSent = await cancelAndSettleOrder(order, marketAccount.publicKey);
if (txsSent && txsSent.length > 0) {
const relevantMint = isBidSide
? marketAccount.account.quoteMint
: marketAccount.account.baseMint;
setBalanceByMint(relevantMint, (oldBalance) => {
const newAmount = oldBalance.uiAmount + balance.toNumber();
return {
...oldBalance,
amount: newAmount.toString(),
uiAmount: newAmount,
uiAmountString: newAmount.toString(),
};
});
}
} catch (err) {
console.error(err);
} finally {
setIsCanceling(false);
}
}, [
order,
proposal,
markets,
wallet.publicKey,
cancelAndSettleOrder,
fetchOpenOrders,
sender,
]);
}, [order, proposal, markets, wallet.publicKey, cancelAndSettleOrder, fetchOpenOrders, sender]);

const handleEdit = useCallback(async () => {
if (!proposal || !markets || !editingOrder) return;

const price =
editedPrice ||
numeral(order.account.openOrders[0].lockedPrice.toString()).multiply(QUOTE_LOTS).value()!;
const size =
editedSize ||
(isBid(order)
? order.account.position.bidsBaseLots
: order.account.position.asksBaseLots
).toNumber();
const oldSize = (
isBidSide ? order.account.position.bidsBaseLots : order.account.position.asksBaseLots
).toNumber();
const size = editedSize || oldSize;
const marketAccount = isPass(order, proposal)
? { publicKey: proposal.account.openbookPassMarket, account: markets.pass }
: { publicKey: proposal.account.openbookFailMarket, account: markets.fail };
const txs = (
await editOrderTransactions({
order,
accountIndex: order.account.openOrders[0].clientId,
amount: size,
price,
limitOrder: true,
ask: !isBid(order),
market: isPass(order, proposal)
? { publicKey: proposal.account.openbookPassMarket, account: markets.pass }
: { publicKey: proposal.account.openbookFailMarket, account: markets.fail },
ask: !isBidSide,
market: marketAccount,
})
)
?.flat()
Expand All @@ -107,6 +111,22 @@ export function ProposalOpenOrderRow({ order }: { order: OpenOrdersAccountWithKe
try {
setIsEditing(true);
await sender.send(txs);
// TODO, once edit working as expected, enable this
// if (txsSent.length > 0) {
// const relevantMint = isBidSide
// ? marketAccount.account.quoteMint
// : marketAccount.account.baseMint;
// const changeInSize = size - oldSize;
// setBalanceByMint(relevantMint, (oldBalance) => {
// const newAmount = (oldBalance.uiAmount ?? 0) - changeInSize;
// return {
// ...oldBalance,
// amount: newAmount.toString(),
// uiAmount: newAmount,
// uiAmountString: newAmount.toString(),
// };
// });
// }
await fetchOpenOrders(wallet.publicKey);
setEditingOrder(undefined);
} finally {
Expand Down Expand Up @@ -141,6 +161,7 @@ export function ProposalOpenOrderRow({ order }: { order: OpenOrdersAccountWithKe

if (!txs) return;
await sender.send(txs);
//TODO add state update here
} finally {
setIsSettling(false);
}
Expand All @@ -165,8 +186,8 @@ export function ProposalOpenOrderRow({ order }: { order: OpenOrdersAccountWithKe
/>
<Stack gap={0} justify="flex-start" align="flex-start">
<Text>{isPass(order, proposal) ? 'PASS' : 'FAIL'}</Text>
<Text size="xs" c={isBid(order) ? theme.colors.green[9] : theme.colors.red[9]}>
{isBid(order) ? 'Bid' : 'Ask'}
<Text size="xs" c={isBidSide ? theme.colors.green[9] : theme.colors.red[9]}>
{isBidSide ? 'Bid' : 'Ask'}
</Text>
</Stack>
</Group>
Expand All @@ -179,17 +200,13 @@ export function ProposalOpenOrderRow({ order }: { order: OpenOrdersAccountWithKe
w="5rem"
variant="filled"
defaultValue={numeral(
isBid(order)
? order.account.position.bidsBaseLots
: order.account.position.asksBaseLots,
isBidSide ? order.account.position.bidsBaseLots : order.account.position.asksBaseLots,
).format(BASE_FORMAT)}
onChange={(e) => setEditedSize(Number(e.target.value))}
/>
) : (
numeral(
isBid(order)
? order.account.position.bidsBaseLots
: order.account.position.asksBaseLots,
isBidSide ? order.account.position.bidsBaseLots : order.account.position.asksBaseLots,
).format(BASE_FORMAT)
)}
</Table.Td>
Expand All @@ -212,21 +229,21 @@ export function ProposalOpenOrderRow({ order }: { order: OpenOrdersAccountWithKe
{/* Notional */}$
{editingOrder === order
? numeral(
(editedPrice || order.account.openOrders[0].lockedPrice * QUOTE_LOTS) *
(editedSize ||
(isBid(order)
? order.account.position.bidsBaseLots
: order.account.position.asksBaseLots)),
).format(NUMERAL_FORMAT)
(editedPrice || order.account.openOrders[0].lockedPrice * QUOTE_LOTS) *
(editedSize ||
(isBidSide
? order.account.position.bidsBaseLots
: order.account.position.asksBaseLots)),
).format(NUMERAL_FORMAT)
: numeral(
isBid(order)
? order.account.position.bidsBaseLots *
order.account.openOrders[0].lockedPrice *
QUOTE_LOTS
: order.account.position.asksBaseLots *
order.account.openOrders[0].lockedPrice *
QUOTE_LOTS,
).format(NUMERAL_FORMAT)}
isBidSide
? order.account.position.bidsBaseLots *
order.account.openOrders[0].lockedPrice *
QUOTE_LOTS
: order.account.position.asksBaseLots *
order.account.openOrders[0].lockedPrice *
QUOTE_LOTS,
).format(NUMERAL_FORMAT)}
</Table.Td>
<Table.Td>
{isPartiallyFilled(order) && (
Expand Down
Loading

0 comments on commit 15bc268

Please sign in to comment.