Skip to content

Commit

Permalink
TRCL-2812 optimization
Browse files Browse the repository at this point in the history
  • Loading branch information
johnqh committed Sep 29, 2023
1 parent 1a84b50 commit 1d86d3a
Show file tree
Hide file tree
Showing 6 changed files with 272 additions and 40 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -46,8 +46,8 @@ async function test(): Promise<void> {
price,
0.01,
clientId,
timeInForce,
goodTilBlock,
timeInForce,
false,
);
console.log('**Order Tx**');
Expand Down
7 changes: 7 additions & 0 deletions v4-client-js/examples/transfer_example_send.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import LocalWallet from '../src/clients/modules/local-wallet';
import { Subaccount } from '../src/clients/subaccount';
import { ValidatorClient } from '../src/clients/validator-client';
import { DYDX_TEST_MNEMONIC } from './constants';

Check failure on line 17 in v4-client-js/examples/transfer_example_send.ts

View workflow job for this annotation

GitHub Actions / CI

There should be at least one empty line between import groups
import { Account } from '@cosmjs/stargate';

Check failure on line 18 in v4-client-js/examples/transfer_example_send.ts

View workflow job for this annotation

GitHub Actions / CI

`@cosmjs/stargate` import should occur before import of `@cosmjs/tendermint-rpc`

// TODO: Test after staging deploy latest transfer contracts.

Expand Down Expand Up @@ -48,9 +49,15 @@ async function test(): Promise<void> {
resolve([msg]);
});

const account: Promise<Account> = client.post.account(
subaccount.address,
undefined,
);

const totalFee = await client.post.simulate(
subaccount.wallet,
() => msgs,
() => account,
GAS_PRICE_DYDX_DENOM,
undefined,
);
Expand Down
6 changes: 6 additions & 0 deletions v4-client-js/examples/transfer_example_withdraw_other.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { EncodeObject } from '@cosmjs/proto-signing';
import { Account } from '@cosmjs/stargate';
import { Method } from '@cosmjs/tendermint-rpc';
import Long from 'long';

Expand Down Expand Up @@ -40,9 +41,14 @@ async function test(): Promise<void> {
resolve([msg]);
});

const account: Promise<Account> = client.post.account(
subaccount.address,
undefined,
);
const totalFee = await client.post.simulate(
subaccount.wallet,
() => msgs,
() => account,
undefined,
);
console.log('**Total Fee**');
Expand Down
128 changes: 109 additions & 19 deletions v4-client-js/src/clients/composite-client.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { EncodeObject } from '@cosmjs/proto-signing';
import { GasPrice, IndexedTx, StdFee } from '@cosmjs/stargate';
import {
Account, GasPrice, IndexedTx, StdFee,
} from '@cosmjs/stargate';
import { BroadcastTxAsyncResponse, BroadcastTxSyncResponse } from '@cosmjs/tendermint-rpc/build/tendermint37';
import { Order_ConditionType, Order_TimeInForce } from '@dydxprotocol/v4-proto/src/codegen/dydxprotocol/clob/order';
import Long from 'long';
Expand Down Expand Up @@ -35,6 +37,14 @@ import { ValidatorClient } from './validator-client';
protobuf.util.Long = Long;
protobuf.configure();

export interface MarketInfo {
clobPairId: number;
atomicResolution: number;
stepBaseQuantums: number;
quantumConversionExponent: number;
subticksPerTick: number;
}

export class CompositeClient {
public readonly network: Network;
private _indexerClient: IndexerClient;
Expand Down Expand Up @@ -86,11 +96,12 @@ export class CompositeClient {
async sign(
wallet: LocalWallet,
messaging: () => Promise<EncodeObject[]>,
account: () => Promise<Account>,
zeroFee: boolean,
gasPrice: GasPrice = GAS_PRICE,
memo?: string,
): Promise<Uint8Array> {
return this.validatorClient.post.sign(wallet, messaging, zeroFee, gasPrice, memo);
return this.validatorClient.post.sign(wallet, messaging, account, zeroFee, gasPrice, memo);
}

/**
Expand All @@ -104,11 +115,12 @@ export class CompositeClient {
async send(
wallet: LocalWallet,
messaging: () => Promise<EncodeObject[]>,
account: () => Promise<Account>,
zeroFee: boolean,
gasPrice: GasPrice = GAS_PRICE,
memo?: string,
): Promise<BroadcastTxAsyncResponse | BroadcastTxSyncResponse | IndexedTx> {
return this.validatorClient.post.send(wallet, messaging, zeroFee, gasPrice, memo);
return this.validatorClient.post.send(wallet, messaging, account, zeroFee, gasPrice, memo);
}

/**
Expand Down Expand Up @@ -142,10 +154,11 @@ export class CompositeClient {
async simulate(
wallet: LocalWallet,
messaging: () => Promise<EncodeObject[]>,
account: () => Promise<Account>,
gasPrice: GasPrice = GAS_PRICE,
memo?: string,
): Promise<StdFee> {
return this.validatorClient.post.simulate(wallet, messaging, gasPrice, memo);
return this.validatorClient.post.simulate(wallet, messaging, account, gasPrice, memo);
}

/**
Expand All @@ -155,9 +168,17 @@ export class CompositeClient {
* at any point.
* @returns The goodTilBlock value
*/
private async calculateGoodTilBlock(): Promise<number> {
const height = await this.validatorClient.get.latestBlockHeight();
return height + 3;

private async calculateGoodTilBlock(
orderFlags: OrderFlags,
currentHeight?: number,
): Promise<number> {
if (orderFlags === OrderFlags.SHORT_TERM) {
const height = currentHeight ?? await this.validatorClient.get.latestBlockHeight();
return height + 3;
} else {
return Promise.resolve(0);
}
}

/**
Expand Down Expand Up @@ -247,9 +268,14 @@ export class CompositeClient {
console.log(err);
});
});
const account: Promise<Account> = this.validatorClient.post.account(
subaccount.address,
undefined,
);
return this.send(
subaccount.wallet,
() => msgs,
() => account,
true);
}

Expand Down Expand Up @@ -292,6 +318,8 @@ export class CompositeClient {
postOnly?: boolean,
reduceOnly?: boolean,
triggerPrice?: number,
marketInfo?: MarketInfo,
currentHeight?: number,
): Promise<BroadcastTxAsyncResponse | BroadcastTxSyncResponse | IndexedTx> {
const msgs: Promise<EncodeObject[]> = new Promise((resolve) => {
const msg = this.placeOrderMessage(
Expand All @@ -309,14 +337,21 @@ export class CompositeClient {
postOnly,
reduceOnly,
triggerPrice,
marketInfo,
currentHeight,
);
msg.then((it) => resolve([it])).catch((err) => {
console.log(err);
});
});
const account: Promise<Account> = this.validatorClient.post.account(
subaccount.address,
undefined,
);
return this.send(
subaccount.wallet,
() => msgs,
() => account,
true);
}

Expand Down Expand Up @@ -360,14 +395,22 @@ export class CompositeClient {
postOnly?: boolean,
reduceOnly?: boolean,
triggerPrice?: number,
marketInfo?: MarketInfo,
currentHeight?: number,
): Promise<EncodeObject> {
const marketsResponse = await this.indexerClient.markets.getPerpetualMarkets(marketId);
const market = marketsResponse.markets[marketId];
const clobPairId = market.clobPairId;
const atomicResolution = market.atomicResolution;
const stepBaseQuantums = market.stepBaseQuantums;
const quantumConversionExponent = market.quantumConversionExponent;
const subticksPerTick = market.subticksPerTick;
const orderFlags = calculateOrderFlags(type, timeInForce);

const result = await Promise.all([
this.calculateGoodTilBlock(orderFlags, currentHeight),
this.retrieveMarketInfo(marketId, marketInfo),
],
);
const goodTilBlock = result[0];
const clobPairId = result[1].clobPairId;
const atomicResolution = result[1].atomicResolution;
const stepBaseQuantums = result[1].stepBaseQuantums;
const quantumConversionExponent = result[1].quantumConversionExponent;
const subticksPerTick = result[1].subticksPerTick;
const orderSide = calculateSide(side);
const quantums = calculateQuantums(
size,
Expand All @@ -380,16 +423,13 @@ export class CompositeClient {
quantumConversionExponent,
subticksPerTick,
);
const orderFlags = calculateOrderFlags(type, timeInForce);
const orderTimeInForce = calculateTimeInForce(type, timeInForce, execution, postOnly);
const goodTilBlock = (orderFlags === OrderFlags.SHORT_TERM)
? await this.calculateGoodTilBlock() : 0;
let goodTilBlockTime = 0;
if (orderFlags === OrderFlags.LONG_TERM || orderFlags === OrderFlags.CONDITIONAL) {
if (goodTilTimeInSeconds == null) {
throw new Error('goodTilTimeInSeconds must be set for LONG_TERM or CONDITIONAL order');
} else {
goodTilBlockTime = await this.calculateGoodTilBlockTime(goodTilTimeInSeconds);
goodTilBlockTime = this.calculateGoodTilBlockTime(goodTilTimeInSeconds);
}
}
const clientMetadata = calculateClientMetadata(type);
Expand Down Expand Up @@ -419,6 +459,27 @@ export class CompositeClient {
);
}

private async retrieveMarketInfo(marketId: string, marketInfo?:MarketInfo): Promise<MarketInfo> {
if (marketInfo) {
return Promise.resolve(marketInfo);
} else {
const marketsResponse = await this.indexerClient.markets.getPerpetualMarkets(marketId);
const market = marketsResponse.markets[marketId];
const clobPairId = market.clobPairId;
const atomicResolution = market.atomicResolution;
const stepBaseQuantums = market.stepBaseQuantums;
const quantumConversionExponent = market.quantumConversionExponent;
const subticksPerTick = market.subticksPerTick;
return {
clobPairId,
atomicResolution,
stepBaseQuantums,
quantumConversionExponent,
subticksPerTick,
};
}
}

/**
* @description Calculate and create the short term place order message
*
Expand Down Expand Up @@ -581,9 +642,14 @@ export class CompositeClient {
);
resolve([msg]);
});
const account: Promise<Account> = this.validatorClient.post.account(
subaccount.address,
undefined,
);
return this.send(
subaccount.wallet,
() => msgs,
() => account,
true);
}

Expand Down Expand Up @@ -638,8 +704,13 @@ export class CompositeClient {
);
resolve([msg]);
});
const account: Promise<Account> = this.validatorClient.post.account(
subaccount.address,
undefined,
);
return this.validatorClient.post.send(subaccount.wallet,
() => msgs,
() => account,
false);
}

Expand Down Expand Up @@ -690,9 +761,14 @@ export class CompositeClient {
);
resolve([msg]);
});
const account: Promise<Account> = this.validatorClient.post.account(
subaccount.address,
undefined,
);
return this.send(
subaccount.wallet,
() => msgs,
() => account,
false);
}

Expand Down Expand Up @@ -784,9 +860,14 @@ export class CompositeClient {
console.log(err);
});
});
const account: Promise<Account> = this.validatorClient.post.account(
subaccount.address,
undefined,
);
const signature = await this.sign(
wallet,
() => msgs,
() => account,
true);

return Buffer.from(signature).toString('base64');
Expand All @@ -812,7 +893,16 @@ export class CompositeClient {
);
resolve([msg]);
});
const signature = await this.sign(subaccount.wallet, () => msgs, true);
const account: Promise<Account> = this.validatorClient.post.account(
subaccount.address,
undefined,
);
const signature = await this.sign(
subaccount.wallet,
() => msgs,
() => account,
true,
);

return Buffer.from(signature).toString('base64');
}
Expand Down
Loading

0 comments on commit 1d86d3a

Please sign in to comment.