-
Notifications
You must be signed in to change notification settings - Fork 88
Expand file tree
/
Copy pathcomposite-client.ts
More file actions
1257 lines (1182 loc) · 40.6 KB
/
composite-client.ts
File metadata and controls
1257 lines (1182 loc) · 40.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { EncodeObject } from '@cosmjs/proto-signing';
import { Account, GasPrice, IndexedTx, StdFee } from '@cosmjs/stargate';
import { Method } from '@cosmjs/tendermint-rpc';
import {
BroadcastTxAsyncResponse,
BroadcastTxSyncResponse,
} from '@cosmjs/tendermint-rpc/build/tendermint37';
import { GetAuthenticatorsResponse } from '@dydxprotocol/v4-proto/src/codegen/dydxprotocol/accountplus/query';
import {
Order_ConditionType,
Order_TimeInForce,
} from '@dydxprotocol/v4-proto/src/codegen/dydxprotocol/clob/order';
import { parseUnits } from 'ethers';
import Long from 'long';
import protobuf from 'protobufjs';
import { bigIntToBytes } from '../lib/helpers';
import { isStatefulOrder, verifyOrderFlags } from '../lib/validation';
import { GovAddNewMarketParams, OrderFlags } from '../types';
import {
AuthenticatorType,
Network,
OrderExecution,
OrderSide,
OrderTimeInForce,
OrderType,
SHORT_BLOCK_FORWARD,
SHORT_BLOCK_WINDOW,
SelectedGasDenom,
} from './constants';
import {
calculateQuantums,
calculateSubticks,
calculateSide,
calculateTimeInForce,
calculateOrderFlags,
calculateClientMetadata,
calculateConditionType,
calculateConditionalOrderTriggerSubticks,
calculateVaultQuantums,
} from './helpers/chain-helpers';
import { IndexerClient } from './indexer-client';
import { UserError } from './lib/errors';
import { generateRegistry } from './lib/registry';
import LocalWallet from './modules/local-wallet';
import { SubaccountInfo } from './subaccount';
import { BroadcastMode, OrderBatch } from './types';
import { ValidatorClient } from './validator-client';
// Required for encoding and decoding queries that are of type Long.
// Must be done once but since the individal modules should be usable
// - must be set in each module that encounters encoding/decoding Longs.
// Reference: https://github.com/protobufjs/protobuf.js/issues/921
protobuf.util.Long = Long;
protobuf.configure();
export interface MarketInfo {
clobPairId: number;
atomicResolution: number;
stepBaseQuantums: number;
quantumConversionExponent: number;
subticksPerTick: number;
}
export interface OrderBatchWithMarketId {
marketId: string;
clobPairId?: number;
clientIds: number[];
}
export interface PermissionedKeysAccountAuth {
authenticators: Long[];
accountForOrder: SubaccountInfo;
}
export class CompositeClient {
public readonly network: Network;
public gasDenom: SelectedGasDenom = SelectedGasDenom.USDC;
private _indexerClient: IndexerClient;
private _validatorClient?: ValidatorClient;
static async connect(network: Network): Promise<CompositeClient> {
const client = new CompositeClient(network);
await client.initialize();
return client;
}
private constructor(network: Network, apiTimeout?: number) {
this.network = network;
this._indexerClient = new IndexerClient(network.indexerConfig, apiTimeout);
}
private async initialize(): Promise<void> {
this._validatorClient = await ValidatorClient.connect(this.network.validatorConfig);
}
get indexerClient(): IndexerClient {
/**
* Get the validator client
*/
return this._indexerClient!;
}
get validatorClient(): ValidatorClient {
/**
* Get the validator client
*/
return this._validatorClient!;
}
get selectedGasDenom(): SelectedGasDenom | undefined {
if (!this._validatorClient) return undefined;
return this._validatorClient.selectedGasDenom;
}
setSelectedGasDenom(gasDenom: SelectedGasDenom): void {
if (!this._validatorClient) throw new Error('Validator client not initialized');
this._validatorClient.setSelectedGasDenom(gasDenom);
}
async populateAccountNumberCache(address: string): Promise<void> {
if (!this._validatorClient) throw new Error('Validator client not initialized');
await this._validatorClient.populateAccountNumberCache(address);
}
/**
* @description Sign a list of messages with a wallet.
* the calling function is responsible for creating the messages.
*
* @throws UnexpectedClientError if a malformed response is returned with no GRPC error
* at any point.
* @returns The Signature.
*/
async sign(
wallet: LocalWallet,
messaging: () => Promise<EncodeObject[]>,
zeroFee: boolean,
gasPrice?: GasPrice,
memo?: string,
account?: () => Promise<Account>,
): Promise<Uint8Array> {
return this.validatorClient.post.sign(wallet, messaging, zeroFee, gasPrice, memo, account);
}
/**
* @description Send a list of messages with a wallet.
* the calling function is responsible for creating the messages.
*
* @throws UnexpectedClientError if a malformed response is returned with no GRPC error
* at any point.
* @returns The Transaction Hash.
*/
async send(
wallet: LocalWallet,
messaging: () => Promise<EncodeObject[]>,
zeroFee: boolean,
gasPrice?: GasPrice,
memo?: string,
broadcastMode?: BroadcastMode,
account?: () => Promise<Account>,
authenticators?: Long[],
): Promise<BroadcastTxAsyncResponse | BroadcastTxSyncResponse | IndexedTx> {
return this.validatorClient.post.send(
wallet,
messaging,
zeroFee,
gasPrice,
memo,
broadcastMode,
account,
undefined,
authenticators,
);
}
/**
* @description Send a signed transaction.
*
* @param signedTransaction The signed transaction to send.
*
* @throws UnexpectedClientError if a malformed response is returned with no GRPC error
* at any point.
* @returns The Transaction Hash.
*/
async sendSignedTransaction(
signedTransaction: Uint8Array,
): Promise<BroadcastTxAsyncResponse | BroadcastTxSyncResponse | IndexedTx> {
return this.validatorClient.post.sendSignedTransaction(signedTransaction);
}
/**
* @description Simulate a list of messages with a wallet.
* the calling function is responsible for creating the messages.
*
* To send multiple messages with gas estimate:
* 1. Client is responsible for creating the messages.
* 2. Call simulate() to get the gas estimate.
* 3. Call send() to send the messages.
*
* @throws UnexpectedClientError if a malformed response is returned with no GRPC error
* at any point.
* @returns The gas estimate.
*/
async simulate(
wallet: LocalWallet,
messaging: () => Promise<EncodeObject[]>,
gasPrice?: GasPrice,
memo?: string,
account?: () => Promise<Account>,
): Promise<StdFee> {
return this.validatorClient.post.simulate(wallet, messaging, gasPrice, memo, account);
}
/**
* @description Calculate the goodTilBlock value for a SHORT_TERM order
*
* @throws UnexpectedClientError if a malformed response is returned with no GRPC error
* at any point.
* @returns The goodTilBlock value
*/
private async calculateGoodTilBlock(
orderFlags: OrderFlags,
currentHeight?: number,
goodTilBlock?: number,
): Promise<number> {
if (orderFlags === OrderFlags.SHORT_TERM) {
if (goodTilBlock !== undefined && goodTilBlock !== 0 && goodTilBlock !== null) {
return Promise.resolve(goodTilBlock);
} else {
const height = currentHeight ?? (await this.validatorClient.get.latestBlockHeight());
return height + SHORT_BLOCK_FORWARD;
}
} else {
return Promise.resolve(0);
}
}
/**
* @description Validate the goodTilBlock value for a SHORT_TERM order
*
* @param goodTilBlock Number of blocks from the current block height the order will
* be valid for.
*
* @throws UserError if the goodTilBlock value is not valid given latest block height and
* SHORT_BLOCK_WINDOW.
*/
private async validateGoodTilBlock(goodTilBlock: number): Promise<void> {
const height = await this.validatorClient.get.latestBlockHeight();
const nextValidBlockHeight = height + 1;
const lowerBound = nextValidBlockHeight;
const upperBound = nextValidBlockHeight + SHORT_BLOCK_WINDOW;
if (goodTilBlock < lowerBound || goodTilBlock > upperBound) {
throw new UserError(`Invalid Short-Term order GoodTilBlock.
Should be greater-than-or-equal-to ${lowerBound} and less-than-or-equal-to ${upperBound}.
Provided good til block: ${goodTilBlock}`);
}
}
/**
* @description Calculate the goodTilBlockTime value for a LONG_TERM order
* the calling function is responsible for creating the messages.
*
* @param goodTilTimeInSeconds The goodTilTimeInSeconds of the order to place.
*
* @throws UnexpectedClientError if a malformed response is returned with no GRPC error
* at any point.
* @returns The goodTilBlockTime value
*/
private calculateGoodTilBlockTime(goodTilTimeInSeconds: number): number {
const now = new Date();
const millisecondsPerSecond = 1000;
const interval = goodTilTimeInSeconds * millisecondsPerSecond;
const future = new Date(now.valueOf() + interval);
return Math.round(future.getTime() / 1000);
}
/**
* @description Place a short term order with human readable input.
*
* Use human readable form of input, including price and size
* The quantum and subticks are calculated and submitted
*
* @param subaccount The subaccount to place the order under
* @param marketId The market to place the order on
* @param side The side of the order to place
* @param price The price of the order to place
* @param size The size of the order to place
* @param clientId The client id of the order to place
* @param timeInForce The time in force of the order to place
* @param goodTilBlock The goodTilBlock of the order to place
* @param reduceOnly The reduceOnly of the order to place
*
*
* @throws UnexpectedClientError if a malformed response is returned with no GRPC error
* at any point.
* @returns The transaction hash.
*/
async placeShortTermOrder(
subaccount: SubaccountInfo,
marketId: string,
side: OrderSide,
price: number,
size: number,
clientId: number,
goodTilBlock: number,
timeInForce: Order_TimeInForce,
reduceOnly: boolean,
memo?: string,
permissionedKeysAccountAuth?: PermissionedKeysAccountAuth,
): Promise<BroadcastTxAsyncResponse | BroadcastTxSyncResponse | IndexedTx> {
// For permissioned orders, use the permissioning account details instead of the subaccount
// This allows placing orders on behalf of another account when using permissioned keys
const accountForOrder = permissionedKeysAccountAuth ? permissionedKeysAccountAuth.accountForOrder : subaccount;
const msgs: Promise<EncodeObject[]> = new Promise((resolve, reject) => {
const msg = this.placeShortTermOrderMessage(
accountForOrder,
marketId,
side,
price,
size,
clientId,
goodTilBlock,
timeInForce,
reduceOnly,
);
msg
.then((it) => {
resolve([it]);
})
.catch((err) => {
console.log(err);
reject(err);
});
});
const account: Promise<Account> = this.validatorClient.post.account(
accountForOrder.address,
undefined,
);
return this.send(
subaccount.wallet,
() => msgs,
true,
undefined,
memo,
undefined,
() => account,
permissionedKeysAccountAuth?.authenticators,
);
}
/**
* @description Place an order with human readable input.
*
* Only MARKET and LIMIT types are supported right now
* Use human readable form of input, including price and size
* The quantum and subticks are calculated and submitted
*
* @param subaccount The subaccount to place the order on.
* @param marketId The market to place the order on.
* @param type The type of order to place.
* @param side The side of the order to place.
* @param price The price of the order to place.
* @param size The size of the order to place.
* @param clientId The client id of the order to place.
* @param timeInForce The time in force of the order to place.
* @param goodTilTimeInSeconds The goodTilTimeInSeconds of the order to place.
* @param execution The execution of the order to place.
* @param postOnly The postOnly of the order to place.
* @param reduceOnly The reduceOnly of the order to place.
* @param triggerPrice The trigger price of conditional orders.
* @param marketInfo optional market information for calculating quantums and subticks.
* This can be constructed from Indexer API. If set to null, additional round
* trip to Indexer API will be made.
* @param currentHeight Current block height. This can be obtained from ValidatorClient.
* If set to null, additional round trip to ValidatorClient will be made.
*
*
* @throws UnexpectedClientError if a malformed response is returned with no GRPC error
* at any point.
* @returns The transaction hash.
*/
async placeOrder(
subaccount: SubaccountInfo,
marketId: string,
type: OrderType,
side: OrderSide,
price: number,
size: number,
clientId: number,
timeInForce?: OrderTimeInForce,
goodTilTimeInSeconds?: number,
execution?: OrderExecution,
postOnly?: boolean,
reduceOnly?: boolean,
triggerPrice?: number,
marketInfo?: MarketInfo,
currentHeight?: number,
goodTilBlock?: number,
memo?: string,
): Promise<BroadcastTxAsyncResponse | BroadcastTxSyncResponse | IndexedTx> {
const msgs: Promise<EncodeObject[]> = new Promise((resolve) => {
const msg = this.placeOrderMessage(
subaccount,
marketId,
type,
side,
price,
size,
clientId,
timeInForce,
goodTilTimeInSeconds,
execution,
postOnly,
reduceOnly,
triggerPrice,
marketInfo,
currentHeight,
goodTilBlock,
);
msg
.then((it) => resolve([it]))
.catch((err) => {
throw err;
});
});
const orderFlags = calculateOrderFlags(type, timeInForce);
const account: Promise<Account> = this.validatorClient.post.account(
subaccount.address,
orderFlags,
);
return this.send(
subaccount.wallet,
() => msgs,
true,
undefined,
memo,
undefined,
() => account,
);
}
/**
* @description Calculate and create the place order message
*
* Only MARKET and LIMIT types are supported right now
* Use human readable form of input, including price and size
* The quantum and subticks are calculated and submitted
*
* @param subaccount The subaccount to place the order under
* @param marketId The market to place the order on
* @param type The type of order to place
* @param side The side of the order to place
* @param price The price of the order to place
* @param size The size of the order to place
* @param clientId The client id of the order to place
* @param timeInForce The time in force of the order to place
* @param goodTilTimeInSeconds The goodTilTimeInSeconds of the order to place
* @param execution The execution of the order to place
* @param postOnly The postOnly of the order to place
* @param reduceOnly The reduceOnly of the order to place
*
*
* @throws UnexpectedClientError if a malformed response is returned with no GRPC error
* at any point.
* @returns The message to be passed into the protocol
*/
private async placeOrderMessage(
subaccount: SubaccountInfo,
marketId: string,
type: OrderType,
side: OrderSide,
price: number,
// trigger_price: number, // not used for MARKET and LIMIT
size: number,
clientId: number,
timeInForce?: OrderTimeInForce,
goodTilTimeInSeconds?: number,
execution?: OrderExecution,
postOnly?: boolean,
reduceOnly?: boolean,
triggerPrice?: number,
marketInfo?: MarketInfo,
currentHeight?: number,
goodTilBlock?: number,
): Promise<EncodeObject> {
const orderFlags = calculateOrderFlags(type, timeInForce);
const result = await Promise.all([
this.calculateGoodTilBlock(orderFlags, currentHeight, goodTilBlock),
this.retrieveMarketInfo(marketId, marketInfo),
]);
const desiredGoodTilBlock = 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, atomicResolution, stepBaseQuantums);
const subticks = calculateSubticks(
price,
atomicResolution,
quantumConversionExponent,
subticksPerTick,
);
const orderTimeInForce = calculateTimeInForce(type, timeInForce, execution, postOnly);
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 = this.calculateGoodTilBlockTime(goodTilTimeInSeconds);
}
}
const clientMetadata = calculateClientMetadata(type);
const conditionalType = calculateConditionType(type);
const conditionalOrderTriggerSubticks = calculateConditionalOrderTriggerSubticks(
type,
atomicResolution,
quantumConversionExponent,
subticksPerTick,
triggerPrice,
);
return this.validatorClient.post.composer.composeMsgPlaceOrder(
subaccount.address,
subaccount.subaccountNumber,
clientId,
clobPairId,
orderFlags,
desiredGoodTilBlock,
goodTilBlockTime,
orderSide,
quantums,
subticks,
orderTimeInForce,
reduceOnly ?? false,
clientMetadata,
conditionalType,
conditionalOrderTriggerSubticks,
);
}
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
*
* Use human readable form of input, including price and size
* The quantum and subticks are calculated and submitted
*
* @param subaccount The subaccount to place the order under
* @param marketId The market to place the order on
* @param side The side of the order to place
* @param price The price of the order to place
* @param size The size of the order to place
* @param clientId The client id of the order to place
* @param timeInForce The time in force of the order to place
* @param goodTilBlock The goodTilBlock of the order to place
* @param reduceOnly The reduceOnly of the order to place
*
*
* @throws UnexpectedClientError if a malformed response is returned with no GRPC error
* at any point.
* @returns The message to be passed into the protocol
*/
private async placeShortTermOrderMessage(
subaccount: SubaccountInfo,
marketId: string,
side: OrderSide,
price: number,
size: number,
clientId: number,
goodTilBlock: number,
timeInForce: Order_TimeInForce,
reduceOnly: boolean,
): Promise<EncodeObject> {
await this.validateGoodTilBlock(goodTilBlock);
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 orderSide = calculateSide(side);
const quantums = calculateQuantums(size, atomicResolution, stepBaseQuantums);
const subticks = calculateSubticks(
price,
atomicResolution,
quantumConversionExponent,
subticksPerTick,
);
const orderFlags = OrderFlags.SHORT_TERM;
return this.validatorClient.post.composer.composeMsgPlaceOrder(
subaccount.address,
subaccount.subaccountNumber,
clientId,
clobPairId,
orderFlags,
goodTilBlock,
0, // Short term orders use goodTilBlock.
orderSide,
quantums,
subticks,
timeInForce,
reduceOnly,
0, // Client metadata is 0 for short term orders.
Order_ConditionType.CONDITION_TYPE_UNSPECIFIED, // Short term orders cannot be conditional.
Long.fromInt(0), // Short term orders cannot be conditional.
);
}
/**
* @description Cancel an order with order information from web socket or REST.
*
* @param subaccount The subaccount to cancel the order from
* @param clientId The client id of the order to cancel
* @param orderFlags The order flags of the order to cancel
* @param clobPairId The clob pair id of the order to cancel
* @param goodTilBlock The goodTilBlock of the order to cancel
* @param goodTilBlockTime The goodTilBlockTime of the order to cancel
*
* @throws UnexpectedClientError if a malformed response is returned with no GRPC error
* at any point.
* @returns The transaction hash.
*/
async cancelRawOrder(
subaccount: SubaccountInfo,
clientId: number,
orderFlags: OrderFlags,
clobPairId: number,
goodTilBlock?: number,
goodTilBlockTime?: number,
): Promise<BroadcastTxAsyncResponse | BroadcastTxSyncResponse | IndexedTx> {
return this.validatorClient.post.cancelOrder(
subaccount,
clientId,
orderFlags,
clobPairId,
goodTilBlock,
goodTilBlockTime,
);
}
/**
* @description Cancel an order with human readable input.
*
* @param subaccount The subaccount to cancel the order from
* @param clientId The client id of the order to cancel
* @param orderFlags The order flags of the order to cancel
* @param marketId The market to cancel the order on
* @param goodTilBlock The goodTilBlock of the order to cancel
* @param goodTilBlockTime The goodTilBlockTime of the order to cancel
*
* @throws UnexpectedClientError if a malformed response is returned with no GRPC error
* at any point.
* @returns The transaction hash.
*/
async cancelOrder(
subaccount: SubaccountInfo,
clientId: number,
orderFlags: OrderFlags,
marketId: string,
goodTilBlock?: number,
goodTilTimeInSeconds?: number,
): Promise<BroadcastTxAsyncResponse | BroadcastTxSyncResponse | IndexedTx> {
const marketsResponse = await this.indexerClient.markets.getPerpetualMarkets(marketId);
const market = marketsResponse.markets[marketId];
const clobPairId = market.clobPairId;
if (!verifyOrderFlags(orderFlags)) {
throw new Error(`Invalid order flags: ${orderFlags}`);
}
let goodTilBlockTime;
if (isStatefulOrder(orderFlags)) {
if (goodTilTimeInSeconds === undefined || goodTilTimeInSeconds === 0) {
throw new Error('goodTilTimeInSeconds must be set for LONG_TERM or CONDITIONAL order');
}
if (goodTilBlock !== 0) {
throw new Error(
'goodTilBlock should be zero since LONG_TERM or CONDITIONAL orders ' +
'use goodTilTimeInSeconds instead of goodTilBlock.',
);
}
goodTilBlockTime = this.calculateGoodTilBlockTime(goodTilTimeInSeconds);
} else {
if (goodTilBlock === undefined || goodTilBlock === 0) {
throw new Error('goodTilBlock must be non-zero for SHORT_TERM orders');
}
if (goodTilTimeInSeconds !== undefined && goodTilTimeInSeconds !== 0) {
throw new Error(
'goodTilTimeInSeconds should be zero since SHORT_TERM orders use goodTilBlock instead of goodTilTimeInSeconds.',
);
}
}
return this.validatorClient.post.cancelOrder(
subaccount,
clientId,
orderFlags,
clobPairId,
goodTilBlock,
goodTilBlockTime,
);
}
/**
* @description Batch cancel short term orders using marketId to clobPairId translation.
*
* @param subaccount The subaccount to cancel the order from
* @param shortTermOrders The list of short term order batches to cancel with marketId
* @param goodTilBlock The goodTilBlock of the order to cancel
* @returns The transaction hash.
*/
async batchCancelShortTermOrdersWithMarketId(
subaccount: SubaccountInfo,
shortTermOrders: OrderBatchWithMarketId[],
goodTilBlock: number,
broadcastMode?: BroadcastMode,
): Promise<BroadcastTxAsyncResponse | BroadcastTxSyncResponse | IndexedTx> {
const orderBatches = await Promise.all(
shortTermOrders.map(async ({ marketId, clobPairId, clientIds }) => ({
clobPairId: (
clobPairId ??
(await this.indexerClient.markets.getPerpetualMarkets(marketId)).markets[marketId]
).clobPairId,
clientIds,
})),
);
return this.validatorClient.post.batchCancelShortTermOrders(
subaccount,
orderBatches,
goodTilBlock,
broadcastMode,
);
}
/**
* @description Batch cancel short term orders using clobPairId.
*
* @param subaccount The subaccount to cancel the order from
* @param shortTermOrders The list of short term order batches to cancel with clobPairId
* @param goodTilBlock The goodTilBlock of the order to cancel
* @returns The transaction hash.
*/
async batchCancelShortTermOrdersWithClobPairId(
subaccount: SubaccountInfo,
shortTermOrders: OrderBatch[],
goodTilBlock: number,
broadcastMode?: BroadcastMode,
): Promise<BroadcastTxAsyncResponse | BroadcastTxSyncResponse | IndexedTx> {
return this.validatorClient.post.batchCancelShortTermOrders(
subaccount,
shortTermOrders,
goodTilBlock,
broadcastMode,
);
}
/**
* @description Transfer from a subaccount to another subaccount
*
* @param subaccount The subaccount to transfer from
* @param recipientAddress The recipient address
* @param recipientSubaccountNumber The recipient subaccount number
* @param amount The amount to transfer
*
* @throws UnexpectedClientError if a malformed response is returned with no GRPC error
* at any point.
* @returns The transaction hash.
*/
async transferToSubaccount(
subaccount: SubaccountInfo,
recipientAddress: string,
recipientSubaccountNumber: number,
amount: string,
memo?: string,
broadcastMode?: BroadcastMode,
): Promise<BroadcastTxAsyncResponse | BroadcastTxSyncResponse | IndexedTx> {
const msgs: Promise<EncodeObject[]> = new Promise((resolve) => {
const msg = this.transferToSubaccountMessage(
subaccount,
recipientAddress,
recipientSubaccountNumber,
amount,
);
resolve([msg]);
});
return this.send(
subaccount.wallet,
() => msgs,
false,
undefined,
memo,
broadcastMode ?? Method.BroadcastTxCommit,
);
}
/**
* @description Create message to transfer from a subaccount to another subaccount
*
* @param subaccount The subaccount to transfer from
* @param recipientAddress The recipient address
* @param recipientSubaccountNumber The recipient subaccount number
* @param amount The amount to transfer
*
*
* @throws UnexpectedClientError if a malformed response is returned with no GRPC error
* at any point.
* @returns The message
*/
transferToSubaccountMessage(
subaccount: SubaccountInfo,
recipientAddress: string,
recipientSubaccountNumber: number,
amount: string,
): EncodeObject {
const validatorClient = this._validatorClient;
if (validatorClient === undefined) {
throw new Error('validatorClient not set');
}
const quantums = parseUnits(amount, validatorClient.config.denoms.USDC_DECIMALS);
if (quantums > BigInt(Long.MAX_VALUE.toString())) {
throw new Error('amount to large');
}
if (quantums < 0) {
throw new Error('amount must be positive');
}
return this.validatorClient.post.composer.composeMsgTransfer(
subaccount.address,
subaccount.subaccountNumber,
recipientAddress,
recipientSubaccountNumber,
0,
Long.fromString(quantums.toString()),
);
}
/**
* @description Deposit from wallet to subaccount
*
* @param subaccount The subaccount to deposit to
* @param amount The amount to deposit
*
* @throws UnexpectedClientError if a malformed response is returned with no GRPC error
* at any point.
* @returns The transaction hash.
*/
async depositToSubaccount(
subaccount: SubaccountInfo,
amount: string,
memo?: string,
): Promise<BroadcastTxAsyncResponse | BroadcastTxSyncResponse | IndexedTx> {
const msgs: Promise<EncodeObject[]> = new Promise((resolve) => {
const msg = this.depositToSubaccountMessage(subaccount, amount);
resolve([msg]);
});
return this.validatorClient.post.send(subaccount.wallet, () => msgs, false, undefined, memo);
}
/**
* @description Create message to deposit from wallet to subaccount
*
* @param subaccount The subaccount to deposit to
* @param amount The amount to deposit
*
* @throws UnexpectedClientError if a malformed response is returned with no GRPC error
* at any point.
* @returns The message
*/
depositToSubaccountMessage(subaccount: SubaccountInfo, amount: string): EncodeObject {
const validatorClient = this._validatorClient;
if (validatorClient === undefined) {
throw new Error('validatorClient not set');
}
const quantums = parseUnits(amount, validatorClient.config.denoms.USDC_DECIMALS);
if (quantums > BigInt(Long.MAX_VALUE.toString())) {
throw new Error('amount to large');
}
if (quantums < 0) {
throw new Error('amount must be positive');
}
return this.validatorClient.post.composer.composeMsgDepositToSubaccount(
subaccount.address,
subaccount.subaccountNumber,
0,
Long.fromString(quantums.toString()),
);
}
/**
* @description Withdraw from subaccount to wallet
*
* @param subaccount The subaccount to withdraw from
* @param amount The amount to withdraw
* @param recipient The recipient address, default to subaccount address
*
* @throws UnexpectedClientError if a malformed response is returned with no GRPC error
* at any point.
* @returns The transaction hash
*/
async withdrawFromSubaccount(
subaccount: SubaccountInfo,
amount: string,
recipient?: string,
memo?: string,
): Promise<BroadcastTxAsyncResponse | BroadcastTxSyncResponse | IndexedTx> {
const msgs: Promise<EncodeObject[]> = new Promise((resolve) => {
const msg = this.withdrawFromSubaccountMessage(subaccount, amount, recipient);
resolve([msg]);
});
return this.send(subaccount.wallet, () => msgs, false, undefined, memo);
}
/**
* @description Create message to withdraw from subaccount to wallet
* with human readable input.
*
* @param subaccount The subaccount to withdraw from
* @param amount The amount to withdraw
* @param recipient The recipient address
*
* @throws UnexpectedClientError if a malformed response is returned with no GRPC error
* at any point.
* @returns The message
*/
withdrawFromSubaccountMessage(
subaccount: SubaccountInfo,
amount: string,
recipient?: string,
): EncodeObject {
const validatorClient = this._validatorClient;
if (validatorClient === undefined) {
throw new Error('validatorClient not set');
}
const quantums = parseUnits(amount, validatorClient.config.denoms.USDC_DECIMALS);
if (quantums > BigInt(Long.MAX_VALUE.toString())) {
throw new Error('amount to large');
}
if (quantums < 0) {
throw new Error('amount must be positive');
}
return this.validatorClient.post.composer.composeMsgWithdrawFromSubaccount(
subaccount.address,
subaccount.subaccountNumber,
0,
Long.fromString(quantums.toString()),
recipient,
);
}
/**
* @description Create message to send chain token from subaccount to wallet
* with human readable input.
*
* @param subaccount The subaccount to withdraw from
* @param amount The amount to withdraw
* @param recipient The recipient address
*
* @throws UnexpectedClientError if a malformed response is returned with no GRPC error
* at any point.
* @returns The message
*/
sendTokenMessage(wallet: LocalWallet, amount: string, recipient: string): EncodeObject {
const address = wallet.address;
if (address === undefined) {
throw new UserError('wallet address is not set. Call connectWallet() first');
}
const { CHAINTOKEN_DENOM: chainTokenDenom, CHAINTOKEN_DECIMALS: chainTokenDecimals } =
this._validatorClient?.config.denoms || {};
if (chainTokenDenom === undefined || chainTokenDecimals === undefined) {
throw new Error('Chain token denom not set in validator config');