chore: use generated types from vega protos - straighten the types, add conversion methods

This commit is contained in:
maciek
2023-06-15 15:39:22 +02:00
parent c2f7ddaeab
commit 7d02dc97d6
15 changed files with 195 additions and 59 deletions
@@ -1,4 +1,4 @@
import { PeggedReference } from '@vegaprotocol/types';
import { vega as vegaProtos } from '@vegaprotocol/protos';
import type { LiquidityProvisionSubmission } from '@vegaprotocol/wallet';
import { createWalletClient, sendVegaTx } from '../capsule/wallet-client';
@@ -32,30 +32,31 @@ export const addVegaWalletSubmitLiquidityProvision = () => {
{
offset: '10',
proportion: '1',
reference: PeggedReference.PEGGED_REFERENCE_MID,
reference: vegaProtos.PeggedReference.PEGGED_REFERENCE_MID,
},
{
offset: '12',
proportion: '2',
reference: PeggedReference.PEGGED_REFERENCE_MID,
reference: vegaProtos.PeggedReference.PEGGED_REFERENCE_MID,
},
],
sells: [
{
offset: '10',
proportion: '2',
reference: PeggedReference.PEGGED_REFERENCE_MID,
reference: vegaProtos.PeggedReference.PEGGED_REFERENCE_MID,
},
{
offset: '12',
proportion: '2',
reference: PeggedReference.PEGGED_REFERENCE_MID,
reference: vegaProtos.PeggedReference.PEGGED_REFERENCE_MID,
},
],
reference: '',
},
pubKey: vegaPubKey,
propagate: true,
};
} as LiquidityProvisionSubmission;
createWalletClient(vegaWalletUrl, token);
@@ -1,7 +1,10 @@
import { AsyncRenderer, Splash } from '@vegaprotocol/ui-toolkit';
import { t } from '@vegaprotocol/i18n';
import { useThrottledDataProvider } from '@vegaprotocol/data-provider';
import { useVegaTransactionStore } from '@vegaprotocol/wallet';
import {
convertDealTicketToOrderSubmission,
useVegaTransactionStore,
} from '@vegaprotocol/wallet';
import { useMarket, marketDataProvider } from '@vegaprotocol/markets';
import { DealTicket } from './deal-ticket';
@@ -45,7 +48,12 @@ export const DealTicketContainer = ({
<DealTicket
market={market}
marketData={marketData}
submit={(orderSubmission) => create({ orderSubmission })}
submit={(dealTicketOrder) =>
create({
orderSubmission:
convertDealTicketToOrderSubmission(dealTicketOrder),
})
}
onClickCollateral={onClickCollateral}
/>
) : (
@@ -9,7 +9,7 @@ import { ExpirySelector } from './expiry-selector';
import { SideSelector } from './side-selector';
import { TimeInForceSelector } from './time-in-force-selector';
import { TypeSelector } from './type-selector';
import type { OrderSubmission } from '@vegaprotocol/wallet';
import type { OrderSubmission } from '@vegaprotocol/protos/dist/vega/commands/v1/OrderSubmission';
import {
normalizeOrderSubmission,
useVegaWallet,
@@ -56,11 +56,12 @@ import { useOrderForm } from '../../hooks/use-order-form';
import { useDataProvider } from '@vegaprotocol/data-provider';
import { marketMarginDataProvider } from '@vegaprotocol/positions';
import type { DealTicketOrderSubmission } from './deal-ticket-container';
export interface DealTicketProps {
market: Market;
marketData: MarketData;
submit: (order: OrderSubmission) => void;
submit: (order: DealTicketOrderSubmission) => void;
onClickCollateral?: () => void;
}
+1 -1
View File
@@ -3,7 +3,7 @@ import type { OrderObj } from '@vegaprotocol/orders';
import { getDefaultOrder, useOrder } from '@vegaprotocol/orders';
import { useEffect } from 'react';
import { useForm } from 'react-hook-form';
import type { OrderSubmission } from '@vegaprotocol/wallet';
import type { OrderSubmission } from '@vegaprotocol/protos/dist/vega/commands/v1/OrderSubmission';
import type { Exact } from 'type-fest';
export type OrderFormFields = OrderObj & {
@@ -9,7 +9,9 @@ import { useHasAmendableOrder } from '../../order-hooks/use-has-amendable-order'
import { useBottomPlaceholder } from '@vegaprotocol/datagrid';
import { useDataProvider } from '@vegaprotocol/data-provider';
import { ordersWithMarketProvider } from '../order-data-provider/order-data-provider';
import type { Transaction } from '@vegaprotocol/wallet';
import {
convertDealTicketToOrderAmendment,
normalizeOrderAmendment,
useVegaTransactionStore,
} from '@vegaprotocol/wallet';
@@ -135,7 +137,7 @@ export const OrderListManager = ({
const cancelAll = useCallback(() => {
create({
orderCancellation: {},
});
} as Transaction);
}, [create]);
return (
@@ -190,7 +192,13 @@ export const OrderListManager = ({
side: editOrder.side,
marketId: editOrder.market.id,
};
create({ orderAmendment }, originalOrder);
create(
{
orderAmendment:
convertDealTicketToOrderAmendment(orderAmendment),
},
originalOrder
);
setEditOrder(null);
}}
/>
+8 -7
View File
@@ -2,11 +2,12 @@ import { useRef } from 'react';
import { usePositionsData } from './use-positions-data';
import { PositionsTable } from './positions-table';
import type { AgGridReact } from 'ag-grid-react';
import * as Schema from '@vegaprotocol/types';
import type { Transaction } from '@vegaprotocol/wallet';
import { useVegaTransactionStore } from '@vegaprotocol/wallet';
import { t } from '@vegaprotocol/i18n';
import { useBottomPlaceholder } from '@vegaprotocol/datagrid';
import { useVegaWallet } from '@vegaprotocol/wallet';
import { vega as vegaProtos } from '@vegaprotocol/protos';
interface PositionsManagerProps {
partyIds: string[];
@@ -45,17 +46,17 @@ export const PositionsManager = ({
submissions: [
{
marketId: marketId,
type: Schema.OrderType.TYPE_MARKET as const,
timeInForce: Schema.OrderTimeInForce.TIME_IN_FORCE_IOC as const,
type: vegaProtos.Order.Type.TYPE_MARKET,
timeInForce: vegaProtos.Order.TimeInForce.TIME_IN_FORCE_IOC,
side: openVolume.startsWith('-')
? Schema.Side.SIDE_BUY
: Schema.Side.SIDE_SELL,
size: openVolume.replace('-', ''),
? vegaProtos.Side.SIDE_BUY
: vegaProtos.Side.SIDE_SELL,
size: BigInt(openVolume.replace('-', '')),
reduceOnly: true,
},
],
},
});
} as Transaction);
const bottomPlaceholderProps = useBottomPlaceholder({
gridRef,
@@ -2,8 +2,9 @@ import { useCallback, useState } from 'react';
import * as Sentry from '@sentry/react';
import { useVegaTransaction, useVegaWallet } from '@vegaprotocol/wallet';
import { useVoteEvent } from './use-vote-event';
import type { VoteValue } from '@vegaprotocol/types';
import { VoteValue } from '@vegaprotocol/types';
import type { VoteEventFieldsFragment } from './__generated__/VoteSubsciption';
import { vega as vegaProtos } from '@vegaprotocol/protos';
export type FinalizedVote = VoteEventFieldsFragment;
@@ -26,7 +27,10 @@ export const useVoteSubmit = () => {
try {
const res = await send(pubKey, {
voteSubmission: {
value: voteValue,
value:
voteValue === VoteValue.VALUE_NO
? vegaProtos.Vote.Value.VALUE_NO
: vegaProtos.Vote.Value.VALUE_YES,
proposalId,
},
});
@@ -1,5 +1,4 @@
import { WalletClientError } from '@vegaprotocol/wallet-client';
import type { LiquidityProvisionSubmission as LiquidityProvisionBody } from '@vegaprotocol/protos/dist/vega/commands/v1/LiquidityProvisionSubmission';
import type { DelegateSubmission } from '@vegaprotocol/protos/dist/vega/commands/v1/DelegateSubmission';
import type { UndelegateSubmission } from '@vegaprotocol/protos/dist/vega/commands/v1/UndelegateSubmission';
@@ -5,6 +5,12 @@ import { ClientErrors } from './connectors';
import { VegaTxStatus, orderErrorResolve } from './use-vega-transaction';
import { useVegaTransactionStore } from './use-vega-transaction-store';
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(BigInt.prototype as any).toJSON = function () {
// put it temporary here, sorry :-(
return this.toString();
};
export const useVegaTransactionManager = () => {
const { sendTx, pubKey, disconnect } = useVegaWallet();
const processed = useRef<Set<number>>(new Set());
@@ -39,6 +45,7 @@ export const useVegaTransactionManager = () => {
})
.catch((err) => {
const error = orderErrorResolve(err);
console.log('error', error, err.toString());
if ((error as WalletError).code === ClientErrors.NO_SERVICE.code) {
disconnect();
}
@@ -2,7 +2,6 @@ import { useVegaTransactionStore } from './use-vega-transaction-store';
import { VegaTxStatus } from './use-vega-transaction';
import type { VegaStoredTxState } from './use-vega-transaction-store';
import type {
OrderAmendmentBody,
OrderCancellationBody,
WithdrawSubmissionBody,
} from './connectors/vega-connector';
@@ -14,6 +13,8 @@ import {
} from '@vegaprotocol/types';
import type { OrderCancellation } from '@vegaprotocol/protos/dist/vega/commands/v1/OrderCancellation';
import type { WithdrawSubmission } from '@vegaprotocol/protos/dist/vega/commands/v1/WithdrawSubmission';
import type { DealTicketOrderAmendment } from './utils';
import { convertDealTicketToOrderAmendment } from './utils';
jest.mock('./utils', () => ({
...jest.requireActual('./utils'),
@@ -36,17 +37,14 @@ describe('useVegaTransactionStore', () => {
} as unknown as WithdrawSubmission,
};
const orderAmendment: OrderAmendmentBody = {
orderAmendment: {
orderId:
'6a4fcd0ba478df2f284ef5f6d3c64a478cb8043d3afe36f66f92c0ed92631e64',
marketId:
'3aa2a828687cc3d59e92445d294891cbbd40e2165bbfb15674158ef5d4e8848d',
price: '1122',
timeInForce: OrderTimeInForce.TIME_IN_FORCE_GTC,
sizeDelta: 0,
},
};
const orderAmendment = {
orderId: '6a4fcd0ba478df2f284ef5f6d3c64a478cb8043d3afe36f66f92c0ed92631e64',
marketId:
'3aa2a828687cc3d59e92445d294891cbbd40e2165bbfb15674158ef5d4e8848d',
price: '1122',
timeInForce: OrderTimeInForce.TIME_IN_FORCE_GTC,
sizeDelta: 0,
} as DealTicketOrderAmendment;
const originalOrder = {
type: OrderType.TYPE_LIMIT,
@@ -103,9 +101,24 @@ describe('useVegaTransactionStore', () => {
});
it('updates an order with order amendment', () => {
useVegaTransactionStore.getState().create(orderAmendment, originalOrder);
useVegaTransactionStore.getState().create(orderAmendment, originalOrder);
useVegaTransactionStore.getState().create(orderAmendment, originalOrder);
useVegaTransactionStore
.getState()
.create(
{ orderAmendment: convertDealTicketToOrderAmendment(orderAmendment) },
originalOrder
);
useVegaTransactionStore
.getState()
.create(
{ orderAmendment: convertDealTicketToOrderAmendment(orderAmendment) },
originalOrder
);
useVegaTransactionStore
.getState()
.create(
{ orderAmendment: convertDealTicketToOrderAmendment(orderAmendment) },
originalOrder
);
const transaction = useVegaTransactionStore.getState().transactions[1];
useVegaTransactionStore
.getState()
+10 -5
View File
@@ -71,6 +71,7 @@ export const useVegaTransactionStore = create<VegaTransactionStore>()(
order,
};
set({ transactions: transactions.concat(transaction) });
console.log('set', transaction);
return transaction.id;
},
update: (index: number, update: Partial<VegaStoredTxState>) => {
@@ -131,30 +132,34 @@ export const useVegaTransactionStore = create<VegaTransactionStore>()(
set(
produce((state: VegaTransactionStore) => {
const transaction = state.transactions.find((transaction) => {
if (!transaction || transaction.status !== VegaTxStatus.Pending) {
if (
!transaction ||
transaction.status !== VegaTxStatus.Pending ||
!transaction?.body
) {
return false;
}
if (
isOrderSubmissionTransaction(transaction?.body) &&
isOrderSubmissionTransaction(transaction.body) &&
transaction.signature &&
order.id === determineId(transaction.signature)
) {
return true;
}
if (
isOrderCancellationTransaction(transaction?.body) &&
isOrderCancellationTransaction(transaction.body) &&
order.id === transaction.body.orderCancellation.orderId
) {
return true;
}
if (
isOrderAmendmentTransaction(transaction?.body) &&
isOrderAmendmentTransaction(transaction.body) &&
order.id === transaction.body.orderAmendment.orderId
) {
return true;
}
if (
isBatchMarketInstructionsTransaction(transaction?.body) &&
isBatchMarketInstructionsTransaction(transaction.body) &&
transaction.signature &&
order.id === determineId(transaction.signature)
) {
+6 -6
View File
@@ -1,9 +1,9 @@
import type { DealTicketOrderSubmission } from './utils';
import {
determineId,
normalizeOrderAmendment,
normalizeOrderSubmission,
} from './utils';
import type { OrderSubmissionBody } from './connectors/vega-connector';
import * as Schema from '@vegaprotocol/types';
describe('determineId', () => {
it('produces a known result for an ID', () => {
@@ -20,7 +20,7 @@ describe('normalizeOrderSubmission', () => {
it('sets and formats price only for limit orders', () => {
expect(
normalizeOrderSubmission(
{ price: '100' } as unknown as OrderSubmissionBody['orderSubmission'],
{ price: '100' } as unknown as DealTicketOrderSubmission,
2,
1
).price
@@ -30,7 +30,7 @@ describe('normalizeOrderSubmission', () => {
{
price: '100',
type: Schema.OrderType.TYPE_LIMIT,
} as unknown as OrderSubmissionBody['orderSubmission'],
} as unknown as DealTicketOrderSubmission,
2,
1
).price
@@ -42,7 +42,7 @@ describe('normalizeOrderSubmission', () => {
normalizeOrderSubmission(
{
expiresAt: '2022-01-01T00:00:00.000Z',
} as OrderSubmissionBody['orderSubmission'],
} as DealTicketOrderSubmission,
2,
1
).expiresAt
@@ -52,7 +52,7 @@ describe('normalizeOrderSubmission', () => {
{
expiresAt: '2022-01-01T00:00:00.000Z',
timeInForce: Schema.OrderTimeInForce.TIME_IN_FORCE_GTT,
} as OrderSubmissionBody['orderSubmission'],
} as DealTicketOrderSubmission,
2,
1
).expiresAt
@@ -64,7 +64,7 @@ describe('normalizeOrderSubmission', () => {
normalizeOrderSubmission(
{
size: '100',
} as OrderSubmissionBody['orderSubmission'],
} as DealTicketOrderSubmission,
2,
1
).size
+94 -7
View File
@@ -1,6 +1,7 @@
import { removeDecimal, toNanoSeconds } from '@vegaprotocol/utils';
import * as Schema from '@vegaprotocol/types';
import type { Market, Order } from '@vegaprotocol/types';
import { OrderTimeInForce, OrderType, AccountType } from '@vegaprotocol/types';
import { OrderTimeInForce, OrderType } from '@vegaprotocol/types';
import BigNumber from 'bignumber.js';
import { ethers } from 'ethers';
import { sha3_256 } from 'js-sha3';
@@ -9,6 +10,33 @@ import type { OrderSubmission } from '@vegaprotocol/protos/dist/vega/commands/v1
import type { OrderAmendment } from '@vegaprotocol/protos/dist/vega/commands/v1/OrderAmendment';
import type { Transaction } from './connectors';
import type { Exact } from 'type-fest';
import { vega as vegaProtos } from '@vegaprotocol/protos';
import type { Side } from '@vegaprotocol/protos/dist/vega/Side';
import type { TimeInForce } from '@vegaprotocol/protos/dist/vega/Order/TimeInForce';
import type { Type } from '@vegaprotocol/protos/dist/vega/Order/Type';
export interface DealTicketOrderSubmission {
marketId: string;
reference?: string;
type: Schema.OrderType;
side: Schema.Side;
timeInForce: Schema.OrderTimeInForce;
size: string;
price?: string;
expiresAt?: string;
postOnly?: boolean;
reduceOnly?: boolean;
}
export interface DealTicketOrderAmendment {
marketId: string;
orderId: string;
reference?: string;
timeInForce: Schema.OrderTimeInForce;
sizeDelta?: number;
price?: string;
expiresAt?: string;
}
/**
* Creates an ID in the same way that core does on the backend. This way we
@@ -28,10 +56,10 @@ export const encodeTransaction = (tx: Transaction): string => {
};
export const normalizeOrderSubmission = (
order: OrderSubmission,
order: DealTicketOrderSubmission,
decimalPlaces: number,
positionDecimalPlaces: number
): OrderSubmission => ({
): DealTicketOrderSubmission => ({
marketId: order.marketId,
reference: order.reference,
type: order.type,
@@ -55,7 +83,7 @@ export const normalizeOrderAmendment = <T extends Exact<OrderAmendment, T>>(
market: Pick<Market, 'id' | 'decimalPlaces' | 'positionDecimalPlaces'>,
price: string,
size: string
): OrderAmendment => ({
): DealTicketOrderAmendment => ({
orderId: order.id,
marketId: market.id,
price: removeDecimal(price, market.decimalPlaces),
@@ -79,13 +107,72 @@ export const normalizeTransfer = <T extends Exact<Transfer, T>>(
}
): Transfer => {
return {
fromAccountType: AccountType.ACCOUNT_TYPE_GENERAL,
fromAccountType: vegaProtos.AccountType.ACCOUNT_TYPE_GENERAL,
to: address,
toAccountType: AccountType.ACCOUNT_TYPE_GENERAL,
toAccountType: vegaProtos.AccountType.ACCOUNT_TYPE_GENERAL,
asset: asset.id,
amount: removeDecimal(amount, asset.decimals),
// oneOff or recurring required otherwise wallet will error
// default oneOff is immediate transfer
oneOff: {},
};
// to be consistent with proto types
kind: null,
reference: '',
} as Transfer;
};
const SideMap: Readonly<Record<Schema.Side, Side>> = {
[Schema.Side.SIDE_BUY]: vegaProtos.Side.SIDE_BUY,
[Schema.Side.SIDE_SELL]: vegaProtos.Side.SIDE_SELL,
[Schema.Side.SIDE_UNSPECIFIED]: vegaProtos.Side.SIDE_UNSPECIFIED,
};
const TimeInForceMap: Readonly<Record<Schema.OrderTimeInForce, TimeInForce>> = {
[Schema.OrderTimeInForce.TIME_IN_FORCE_FOK]:
vegaProtos.Order.TimeInForce.TIME_IN_FORCE_FOK,
[Schema.OrderTimeInForce.TIME_IN_FORCE_GFA]:
vegaProtos.Order.TimeInForce.TIME_IN_FORCE_GFA,
[Schema.OrderTimeInForce.TIME_IN_FORCE_GFN]:
vegaProtos.Order.TimeInForce.TIME_IN_FORCE_GFN,
[Schema.OrderTimeInForce.TIME_IN_FORCE_GTC]:
vegaProtos.Order.TimeInForce.TIME_IN_FORCE_GTC,
[Schema.OrderTimeInForce.TIME_IN_FORCE_GTT]:
vegaProtos.Order.TimeInForce.TIME_IN_FORCE_GTT,
[Schema.OrderTimeInForce.TIME_IN_FORCE_IOC]:
vegaProtos.Order.TimeInForce.TIME_IN_FORCE_IOC,
};
const TypeMap: Readonly<Record<Schema.OrderType, Type>> = {
[Schema.OrderType.TYPE_LIMIT]: vegaProtos.Order.Type.TYPE_LIMIT,
[Schema.OrderType.TYPE_MARKET]: vegaProtos.Order.Type.TYPE_MARKET,
[Schema.OrderType.TYPE_NETWORK]: vegaProtos.Order.Type.TYPE_NETWORK,
// [undefined]: vegaProtos.Order.Type.TYPE_UNSPECIFIED,
};
export const convertDealTicketToOrderSubmission = (
dealTicketOrder: DealTicketOrderSubmission
) => {
return {
...dealTicketOrder,
expiresAt: dealTicketOrder.expiresAt
? BigInt(dealTicketOrder.expiresAt)
: null,
size: BigInt(dealTicketOrder.size),
side: SideMap[dealTicketOrder.side],
timeInForce: TimeInForceMap[dealTicketOrder.timeInForce],
type: TypeMap[dealTicketOrder.type],
} as OrderSubmission;
};
export const convertDealTicketToOrderAmendment = (
dealTicketOrder: DealTicketOrderAmendment
) => {
return {
...dealTicketOrder,
expiresAt: dealTicketOrder.expiresAt
? BigInt(dealTicketOrder.expiresAt)
: null,
timeInForce: TimeInForceMap[dealTicketOrder.timeInForce],
sizeDelta: BigInt(dealTicketOrder.sizeDelta || 0),
} as OrderAmendment;
};
@@ -1,5 +1,6 @@
import { t } from '@vegaprotocol/i18n';
import { Dialog } from '@vegaprotocol/ui-toolkit';
import type { Transaction } from '@vegaprotocol/wallet';
import { useVegaWallet } from '@vegaprotocol/wallet';
import { WithdrawFormContainer } from './withdraw-form-container';
import { useWeb3ConnectStore } from '@vegaprotocol/web3';
@@ -22,7 +23,7 @@ export const CreateWithdrawalDialog = () => {
>
<WithdrawFormContainer
assetId={assetId}
partyId={pubKey ? pubKey : undefined}
partyId={pubKey || undefined}
submit={({ amount, asset, receiverAddress }) => {
createTransaction({
withdrawSubmission: {
@@ -34,7 +35,7 @@ export const CreateWithdrawalDialog = () => {
},
},
},
});
} as Transaction);
close();
}}
/>
@@ -1,3 +1,4 @@
import type { Transaction } from '@vegaprotocol/wallet';
import {
useVegaTransaction,
useVegaWallet,
@@ -52,7 +53,7 @@ export const useCreateWithdraw = () => {
},
},
},
});
} as Transaction);
if (res) {
const withdrawalId = determineId(res.signature);