-
Notifications
You must be signed in to change notification settings - Fork 88
Expand file tree
/
Copy pathclient.py
More file actions
1530 lines (1298 loc) · 52.3 KB
/
client.py
File metadata and controls
1530 lines (1298 loc) · 52.3 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 asyncio
import base64
import json
from dataclasses import dataclass
from decimal import Decimal
from typing import Union, Dict, Any
import grpc
from google._upb._message import Message
from google.protobuf.json_format import MessageToDict
from typing_extensions import List, Optional, Self
from dydx_v4_client import OrderFlags
from dydx_v4_client.indexer.rest.constants import OrderType
from dydx_v4_client.node.market import Market
from dydx_v4_client.node_helper_type import ExtendedSubaccount
from dydx_v4_client.utility import convert_quantum_bytes_to_value_with_order_side
from dydx_v4_client import OrderFlags
from dydx_v4_client.indexer.rest.constants import OrderType
from dydx_v4_client.node.market import Market
from dydx_v4_client.node_helper_type import ExtendedSubaccount
from dydx_v4_client.utility import convert_quantum_bytes_to_value_with_order_side
from v4_proto.cosmos.auth.v1beta1 import query_pb2_grpc as auth
from v4_proto.cosmos.auth.v1beta1.auth_pb2 import BaseAccount
from v4_proto.cosmos.auth.v1beta1.query_pb2 import QueryAccountRequest
from v4_proto.cosmos.bank.v1beta1 import query_pb2 as bank_query
from v4_proto.cosmos.bank.v1beta1 import query_pb2_grpc as bank_query_grpc
from v4_proto.cosmos.base.tendermint.v1beta1 import query_pb2 as tendermint_query
from v4_proto.cosmos.base.tendermint.v1beta1 import (
query_pb2_grpc as tendermint_query_grpc,
)
from v4_proto.cosmos.base.query.v1beta1 import pagination_pb2 as pagination_query
from v4_proto.cosmos.staking.v1beta1 import query_pb2 as staking_query
from v4_proto.cosmos.staking.v1beta1 import query_pb2_grpc as staking_query_grpc
from v4_proto.cosmos.distribution.v1beta1 import query_pb2 as distribution_query
from v4_proto.cosmos.distribution.v1beta1 import (
query_pb2_grpc as distribution_query_grpc,
tx_pb2,
)
from v4_proto.cosmos.tx.v1beta1 import service_pb2_grpc
from v4_proto.cosmos.tx.v1beta1.service_pb2 import (
BroadcastMode,
BroadcastTxRequest,
SimulateRequest,
GetTxRequest,
)
from v4_proto.cosmos.gov.v1 import query_pb2 as gov_query
from v4_proto.cosmos.gov.v1 import query_pb2_grpc as gov_query_grpc
from v4_proto.cosmos.tx.v1beta1.tx_pb2 import Tx
from v4_proto.dydxprotocol.accountplus import query_pb2 as accountplus_query
from v4_proto.dydxprotocol.accountplus import query_pb2_grpc as accountplus_query_grpc
from v4_proto.dydxprotocol.bridge import query_pb2 as bridge_query
from v4_proto.dydxprotocol.bridge import query_pb2_grpc as bridge_query_grpc
from v4_proto.dydxprotocol.clob import clob_pair_pb2 as clob_pair_type
from v4_proto.dydxprotocol.clob import (
equity_tier_limit_config_pb2 as equity_tier_limit_config_type,
)
from v4_proto.dydxprotocol.clob import query_pb2 as clob_query
from v4_proto.dydxprotocol.clob import query_pb2_grpc as clob_query_grpc
from v4_proto.dydxprotocol.clob.order_pb2 import Order, OrderId
from v4_proto.dydxprotocol.clob.query_pb2 import (
QueryAllClobPairRequest,
QueryClobPairAllResponse,
QueryLeverageRequest,
QueryLeverageResponse,
)
from v4_proto.dydxprotocol.feetiers import query_pb2 as fee_tier_query
from v4_proto.dydxprotocol.feetiers import query_pb2_grpc as fee_tier_query_grpc
from v4_proto.dydxprotocol.perpetuals import query_pb2_grpc as perpetuals_query_grpc
from v4_proto.dydxprotocol.perpetuals.query_pb2 import (
QueryAllPerpetualsRequest,
QueryAllPerpetualsResponse,
QueryPerpetualRequest,
QueryPerpetualResponse,
)
from v4_proto.dydxprotocol.prices import market_price_pb2 as market_price_type
from v4_proto.dydxprotocol.prices import query_pb2_grpc as prices_query_grpc
from v4_proto.dydxprotocol.prices.query_pb2 import (
QueryAllMarketPricesRequest,
QueryAllMarketPricesResponse,
QueryMarketPriceRequest,
)
from v4_proto.dydxprotocol.revshare.revshare_pb2 import OrderRouterRevShare
from v4_proto.dydxprotocol.rewards import query_pb2 as rewards_query
from v4_proto.dydxprotocol.rewards import query_pb2_grpc as rewards_query_grpc
from v4_proto.dydxprotocol.stats import query_pb2 as stats_query
from v4_proto.dydxprotocol.stats import query_pb2_grpc as stats_query_grpc
from v4_proto.dydxprotocol.subaccounts import query_pb2 as subaccount_query
from v4_proto.dydxprotocol.subaccounts import query_pb2_grpc as subaccounts_query_grpc
from v4_proto.dydxprotocol.subaccounts import subaccount_pb2 as subaccount_type
from v4_proto.dydxprotocol.subaccounts.query_pb2 import (
QueryAllSubaccountRequest,
QueryGetSubaccountRequest,
QuerySubaccountAllResponse,
)
from v4_proto.dydxprotocol.subaccounts.subaccount_pb2 import SubaccountId
from v4_proto.dydxprotocol.clob.tx_pb2 import OrderBatch
from v4_proto.dydxprotocol.ratelimit import query_pb2 as rate_query
from v4_proto.dydxprotocol.ratelimit import query_pb2_grpc as rate_query_grpc
from v4_proto.dydxprotocol.affiliates import query_pb2 as affiliate_query
from v4_proto.dydxprotocol.affiliates import query_pb2_grpc as affiliate_query_grpc
from v4_proto.dydxprotocol.revshare import query_pb2_grpc as revshare_query_grpc
from v4_proto.dydxprotocol.revshare import query_pb2 as revshare_query
from v4_proto.dydxprotocol.revshare import tx_pb2_grpc as revshare_tx_grpc
from v4_proto.dydxprotocol.revshare import tx_pb2 as revshare_tx_query
from v4_proto.dydxprotocol.revshare import params_pb2 as revshare_param
from v4_proto.dydxprotocol.revshare import revshare_pb2
from dydx_v4_client.network import NodeConfig
from dydx_v4_client.node.authenticators import Authenticator, validate_authenticator
from dydx_v4_client.node.builder import Builder, TxOptions
from dydx_v4_client.node.fee import Coin, Fee, calculate_fee, Denom
from dydx_v4_client.node.message import (
cancel_order,
deposit,
place_order,
send_token,
transfer,
withdraw,
batch_cancel,
add_authenticator,
remove_authenticator,
create_market_permissionless,
register_affiliate,
withdraw_delegator_reward,
undelegate,
delegate,
update_leverage,
)
from dydx_v4_client.wallet import Wallet
DEFAULT_QUERY_TIMEOUT_SECS = 15
DEFAULT_QUERY_INTERVAL_SECS = 2
GOOD_TIL_BLOCK_OFFSET = 20
class CustomJSONDecoder:
def __init__(self):
self.decoder = json.JSONDecoder(object_hook=self.decode_dict)
def decode(self, json_string):
return self.decoder.decode(json_string)
@staticmethod
def decode_base64(value):
if isinstance(value, str):
try:
return list(base64.b64decode(value))
except (base64.binascii.Error, ValueError):
return value
return value
def decode_dict(self, data):
if isinstance(data, dict):
return {k: self.decode_base64(v) for k, v in data.items()}
return data
@dataclass
class QueryNodeClient:
channel: grpc.Channel
@staticmethod
def transcode_response(response: Message) -> Union[Dict[str, Any], List[Any]]:
"""
Encodes the response using the custom JSON encoder.
Args:
response (Message): The response message to encode.
Returns:
Union[Dict[str, Any], List[Any]]: The encoded response.
"""
response_dict = MessageToDict(response)
json_string = json.dumps(response_dict)
return CustomJSONDecoder().decode(json_string)
async def get_account_balances(
self, address: str
) -> bank_query.QueryAllBalancesResponse:
"""
Retrieves all account balances for a given address.
Args:
address (str): The account address.
Returns:
bank_query.QueryAllBalancesResponse: The response containing all account balances.
"""
stub = bank_query_grpc.QueryStub(self.channel)
return stub.AllBalances(bank_query.QueryAllBalancesRequest(address=address))
async def get_account_balance(
self, address: str, denom: str
) -> bank_query.QueryBalanceResponse:
"""
Retrieves the account balance for a specific denomination.
Args:
address (str): The account address.
denom (str): The denomination of the balance.
Returns:
bank_query.QueryBalanceResponse: The response containing the account balance.
"""
stub = bank_query_grpc.QueryStub(self.channel)
return stub.Balance(
bank_query.QueryBalanceRequest(address=address, denom=denom)
)
async def get_account(self, address: str) -> BaseAccount:
"""
Retrieves the account information for a given address.
Args:
address (str): The account address.
Returns:
BaseAccount: The base account information.
"""
account = BaseAccount()
response = auth.QueryStub(self.channel).Account(
QueryAccountRequest(address=address)
)
if not response.account.Unpack(account):
raise Exception("Failed to unpack account")
return account
async def latest_block(self) -> tendermint_query.GetLatestBlockResponse:
"""
Retrieves the latest block information.
Returns:
tendermint_query.GetLatestBlockResponse: The response containing the latest block information.
"""
return tendermint_query_grpc.ServiceStub(self.channel).GetLatestBlock(
tendermint_query.GetLatestBlockRequest()
)
async def latest_block_height(self) -> int:
"""
Retrieves the height of the latest block.
Returns:
int: The height of the latest block.
"""
block = await self.latest_block()
return block.block.header.height
async def get_user_stats(self, address: str) -> stats_query.QueryUserStatsResponse:
"""
Retrieves the user stats for a given address.
Args:
address (str): The user address.
Returns:
stats_query.QueryUserStatsResponse: The response containing the user stats.
"""
stub = stats_query_grpc.QueryStub(self.channel)
return stub.UserStats(stats_query.QueryUserStatsRequest(user=address))
async def get_all_validators(
self, status: str = ""
) -> staking_query.QueryValidatorsResponse:
"""
Retrieves all validators with an optional status filter.
Args:
status (str, optional): The validator status filter. Defaults to an empty string.
Returns:
staking_query.QueryValidatorsResponse: The response containing all validators.
"""
stub = staking_query_grpc.QueryStub(self.channel)
return stub.Validators(staking_query.QueryValidatorsRequest(status=status))
async def get_subaccount(
self, address: str, account_number: int
) -> ExtendedSubaccount:
"""
Retrieves a subaccount for a given address and account number.
Args:
address (str): The owner address.
account_number (int): The subaccount number.
Returns:
Optional[subaccount_type.Subaccount]: The subaccount, if found.
"""
stub = subaccounts_query_grpc.QueryStub(self.channel)
response = stub.Subaccount(
QueryGetSubaccountRequest(owner=address, number=account_number)
)
return ExtendedSubaccount(response.subaccount)
async def get_subaccounts(self) -> QuerySubaccountAllResponse:
"""
Retrieves all subaccounts.
Returns:
QuerySubaccountAllResponse: The response containing all subaccounts.
"""
stub = subaccounts_query_grpc.QueryStub(self.channel)
return stub.SubaccountAll(QueryAllSubaccountRequest())
async def get_clob_pair(self, pair_id: int) -> clob_pair_type.ClobPair:
"""
Retrieves a CLOB pair by its ID.
Args:
pair_id (int): The CLOB pair ID.
Returns:
clob_pair_type.ClobPair: The CLOB pair.
"""
stub = clob_query_grpc.QueryStub(self.channel)
response = stub.ClobPair(clob_query.QueryGetClobPairRequest(id=pair_id))
return response.clob_pair
async def get_clob_pairs(self) -> QueryClobPairAllResponse:
"""
Retrieves all CLOB pairs.
Returns:
QueryClobPairAllResponse: The response containing all CLOB pairs.
"""
stub = clob_query_grpc.QueryStub(self.channel)
return stub.ClobPairAll(QueryAllClobPairRequest())
async def get_leverage(
self, address: str, subaccount_number: int
) -> QueryLeverageResponse:
"""
Retrieves leverage information for a subaccount.
Args:
address (str): The subaccount owner address.
subaccount_number (int): The subaccount number.
Returns:
QueryLeverageResponse: The response containing leverage information.
"""
stub = clob_query_grpc.QueryStub(self.channel)
return stub.Leverage(
QueryLeverageRequest(owner=address, number=subaccount_number)
)
async def get_price(self, market_id: int) -> market_price_type.MarketPrice:
"""
Retrieves the market price for a given market ID.
Args:
market_id (int): The market ID.
Returns:
market_price_type.MarketPrice: The market price.
"""
stub = prices_query_grpc.QueryStub(self.channel)
response = stub.MarketPrice(QueryMarketPriceRequest(id=market_id))
return response.market_price
async def get_prices(self) -> QueryAllMarketPricesResponse:
"""
Retrieves all market prices.
Returns:
QueryAllMarketPricesResponse: The response containing all market prices.
"""
stub = prices_query_grpc.QueryStub(self.channel)
return stub.AllMarketPrices(QueryAllMarketPricesRequest())
async def get_perpetual(self, perpetual_id: int) -> QueryPerpetualResponse:
"""
Retrieves a perpetual by its ID.
Args:
perpetual_id (int): The perpetual ID.
Returns:
QueryPerpetualResponse: The response containing the perpetual.
"""
stub = perpetuals_query_grpc.QueryStub(self.channel)
return stub.Perpetual(QueryPerpetualRequest(id=perpetual_id))
async def get_perpetuals(self) -> QueryAllPerpetualsResponse:
"""
Retrieves all perpetuals.
Returns:
QueryAllPerpetualsResponse: The response containing all perpetuals.
"""
stub = perpetuals_query_grpc.QueryStub(self.channel)
return stub.AllPerpetuals(QueryAllPerpetualsRequest())
async def get_equity_tier_limit_config(
self,
) -> equity_tier_limit_config_type.EquityTierLimitConfiguration:
"""
Retrieves the equity tier limit configuration.
Returns:
equity_tier_limit_config_type.EquityTierLimitConfiguration: The equity tier limit configuration.
"""
stub = clob_query_grpc.QueryStub(self.channel)
response = stub.EquityTierLimitConfiguration(
clob_query.QueryEquityTierLimitConfigurationRequest()
)
return response.equity_tier_limit_config
async def get_delegator_delegations(
self, delegator_addr: str
) -> staking_query.QueryDelegatorDelegationsResponse:
"""
Retrieves the delegations for a given delegator address.
Args:
delegator_addr (str): The delegator address.
Returns:
staking_query.QueryDelegatorDelegationsResponse: The response containing the delegator delegations.
"""
stub = staking_query_grpc.QueryStub(self.channel)
return stub.DelegatorDelegations(
staking_query.QueryDelegatorDelegationsRequest(
delegator_addr=delegator_addr
)
)
async def get_delegator_unbonding_delegations(
self, delegator_addr: str
) -> staking_query.QueryDelegatorUnbondingDelegationsResponse:
"""
Retrieves the unbonding delegations for a given delegator address.
Args:
delegator_addr (str): The delegator address.
Returns:
staking_query.QueryDelegatorUnbondingDelegationsResponse: The response containing the delegator unbonding delegations.
"""
stub = staking_query_grpc.QueryStub(self.channel)
return stub.DelegatorUnbondingDelegations(
staking_query.QueryDelegatorUnbondingDelegationsRequest(
delegator_addr=delegator_addr
)
)
async def get_delayed_complete_bridge_messages(
self, address: str = ""
) -> bridge_query.QueryDelayedCompleteBridgeMessagesResponse:
"""
Retrieves the delayed complete bridge messages for a given address.
Args:
address (str, optional): The address. Defaults to an empty string.
Returns:
bridge_query.QueryDelayedCompleteBridgeMessagesResponse: The response containing the delayed complete bridge messages.
"""
stub = bridge_query_grpc.QueryStub(self.channel)
return stub.DelayedCompleteBridgeMessages(
bridge_query.QueryDelayedCompleteBridgeMessagesRequest(address=address)
)
async def get_fee_tiers(self) -> fee_tier_query.QueryPerpetualFeeParamsResponse:
"""
Retrieves the perpetual fee parameters.
Returns:
fee_tier_query.QueryPerpetualFeeParamsResponse: The response containing the perpetual fee parameters.
"""
stub = fee_tier_query_grpc.QueryStub(self.channel)
return stub.PerpetualFeeParams(fee_tier_query.QueryPerpetualFeeParamsRequest())
async def get_user_fee_tier(
self, address: str
) -> fee_tier_query.QueryUserFeeTierResponse:
"""
Retrieves the user fee tier for a given address.
Args:
address (str): The user address.
Returns:
fee_tier_query.QueryUserFeeTierResponse: The response containing the user fee tier.
"""
stub = fee_tier_query_grpc.QueryStub(self.channel)
return stub.UserFeeTier(fee_tier_query.QueryUserFeeTierRequest(user=address))
async def get_rewards_params(self) -> rewards_query.QueryParamsResponse:
"""
Retrieves the rewards parameters.
Returns:
rewards_query.QueryParamsResponse: The response containing the rewards parameters.
"""
stub = rewards_query_grpc.QueryStub(self.channel)
return stub.Params(rewards_query.QueryParamsRequest())
async def get_authenticators(
self, address: str
) -> accountplus_query.GetAuthenticatorsResponse:
stub = accountplus_query_grpc.QueryStub(self.channel)
return stub.GetAuthenticators(
accountplus_query.GetAuthenticatorsRequest(account=address)
)
async def get_node_info(self) -> tendermint_query.GetNodeInfoResponse:
"""
Query for node info.
Returns:
tendermint_query.GetNodeInfoResponse: The response containing the node information.
"""
return tendermint_query_grpc.ServiceStub(self.channel).GetNodeInfo(
tendermint_query.GetNodeInfoRequest()
)
async def get_delegation_total_rewards(
self, address: str
) -> distribution_query.QueryDelegationTotalRewardsResponse:
"""
Get all unbonding delegations from a delegator.
Args:
address (str): The delegator address
Returns:
distribution_query.QueryDelegationTotalRewardsResponse: All unbonding delegations from a delegator.
"""
return distribution_query_grpc.QueryStub(self.channel).DelegationTotalRewards(
distribution_query.QueryDelegationTotalRewardsRequest(
delegator_address=address
)
)
async def get_all_gov_proposals(
self,
proposal_status: Optional[str] = None,
voter: Optional[str] = None,
depositor: Optional[str] = None,
key: Optional[bytes] = None,
offset: Optional[int] = None,
limit: Optional[int] = None,
count_total: Optional[bool] = False,
reverse: Optional[bool] = False,
) -> gov_query.QueryProposalsResponse:
"""
Query all gov proposals
Args:
proposal_status (Optional[ProposalStatus]): Status of the proposal to filter by.
voter (Optional[str]): Voter to filter by.
depositor (Optional[str]): Depositor to filter by.
key (Optional[byte]): Key to filter by.
offset (Optional[int]): Offset number.
limit (Optional[int]): Number of items to retrieve.
count_total (Optional[bool]): Filter to return total count or not
reverse (Optional[bool]): Direction of the list
"""
return gov_query_grpc.QueryStub(self.channel).Proposals(
gov_query.QueryProposalsRequest(
proposal_status=proposal_status,
voter=voter,
depositor=depositor,
pagination=pagination_query.PageRequest(
key=key,
offset=offset,
limit=limit,
count_total=count_total,
reverse=reverse,
),
)
)
async def get_withdrawal_and_transfer_gating_status(
self, perpetual_id: int
) -> subaccount_query.QueryGetWithdrawalAndTransfersBlockedInfoResponse:
"""
Query the status of the withdrawal and transfer gating
Args:
perpetual_id (int): The perpetual ID.
Returns:
subaccount_query.QueryGetWithdrawalAndTransfersBlockedInfoResponse: Withdrawal and transfer gating status of the perpetual id
"""
return subaccounts_query_grpc.QueryStub(
self.channel
).GetWithdrawalAndTransfersBlockedInfo(
subaccount_query.QueryGetWithdrawalAndTransfersBlockedInfoRequest(
perpetual_id=perpetual_id
)
)
async def get_withdrawal_capacity_by_denom(
self, denom: str
) -> rate_query.QueryCapacityByDenomResponse:
"""
Query withdrawal capacity by denomination value
Args:
denom (str): Denomination identifier
Returns:
rate_query.QueryCapacityByDenomResponse: Return withdraw capacity
"""
return rate_query_grpc.QueryStub(self.channel).CapacityByDenom(
rate_query.QueryCapacityByDenomRequest(denom=denom)
)
async def get_affiliate_info(
self, address: str
) -> affiliate_query.AffiliateInfoResponse:
"""
Query affiliate information of an address
Args:
address (str): Address to get affiliate information of
Returns:
affiliate_query.AffiliateInfoResponse: Affiliate information of the address
"""
return affiliate_query_grpc.QueryStub(self.channel).AffiliateInfo(
affiliate_query.AffiliateInfoRequest(address=address)
)
async def get_referred_by(self, address: str) -> affiliate_query.ReferredByResponse:
"""
Query to reference information by address
Args:
address (str): Address to get referred by information
Returns:
affiliate_query.ReferredByResponse: Referred by information
"""
return affiliate_query_grpc.QueryStub(self.channel).ReferredBy(
affiliate_query.ReferredByRequest(address=address)
)
async def get_all_affiliate_tiers(
self,
) -> affiliate_query.AllAffiliateTiersResponse:
"""
Query all affiliate tiers
Returns:
affiliate_query.AllAffiliateTiersResponse: All affiliate tiers
"""
return affiliate_query_grpc.QueryStub(self.channel).AllAffiliateTiers(
affiliate_query.AllAffiliateTiersRequest()
)
async def get_affiliate_whitelist(
self,
) -> affiliate_query.AffiliateWhitelistResponse:
"""
Query whitelisted affiliate information
Returns:
affiliate_query.AffiliateWhitelistResponse: List of whitelisted affiliate
"""
return affiliate_query_grpc.QueryStub(self.channel).AffiliateWhitelist(
affiliate_query.AffiliateWhitelistRequest()
)
async def get_market_mapper_revenue_share_param(
self,
) -> revshare_query.QueryMarketMapperRevenueShareParamsResponse:
"""
Query revenue share params
Returns:
revshare_query.QueryMarketMapperRevenueShareParamsResponse: Market mapper revenue share parameters
"""
return revshare_query_grpc.QueryStub(
self.channel
).MarketMapperRevenueShareParams(
revshare_query.QueryMarketMapperRevenueShareParams()
)
async def get_market_mapper_revenue_share_details(
self, market_id: int
) -> revshare_query.QueryMarketMapperRevShareDetailsResponse:
"""
Query revenue share details by market id
Args:
market_id(int): Market id to query
Returns:
revshare_query.QueryMarketMapperRevShareDetailsResponse: Details of market mapper revenue share
"""
return revshare_query_grpc.QueryStub(self.channel).MarketMapperRevShareDetails(
revshare_query.QueryMarketMapperRevShareDetails(market_id=market_id)
)
async def get_unconditional_revenue_sharing_config(
self,
) -> revshare_query.QueryUnconditionalRevShareConfigResponse:
"""
Query configuration of unconditional revenue sharing
Returns:
revshare_query.QueryUnconditionalRevShareConfigResponse: The configuration of unconditional revenue sharing
"""
return revshare_query_grpc.QueryStub(self.channel).UnconditionalRevShareConfig(
revshare_query.QueryUnconditionalRevShareConfig()
)
async def get_order_router_revenue_share(
self, address: str
) -> revshare_query.QueryOrderRouterRevShareResponse:
"""
Query order router revenue share of certain address
Args:
address(str): Address to fetch order router revenue share of
Returns:
revshare_query.QueryOrderRouterRevShareResponse: Order router revenue share response
"""
return revshare_query_grpc.QueryStub(self.channel).OrderRouterRevShare(
revshare_query.QueryOrderRouterRevShare(address=address)
)
class SequenceManager:
def __init__(self, query_node_client: QueryNodeClient):
self.query_node_client = query_node_client
async def before_send(self, wallet: Wallet):
if self.query_node_client:
account = await self.query_node_client.get_account(wallet.address)
wallet.sequence = account.sequence
async def after_send(self, wallet: Wallet):
if not self.query_node_client:
wallet.sequence += 1
@dataclass
class MutatingNodeClient(QueryNodeClient):
builder: Builder
sequence_manager: SequenceManager = None
async def broadcast(self, transaction: Tx, mode=BroadcastMode.BROADCAST_MODE_SYNC):
"""
Broadcasts a transaction.
Args:
transaction (Tx): The transaction to broadcast.
mode (BroadcastMode, optional): The broadcast mode. Defaults to BroadcastMode.BROADCAST_MODE_SYNC.
Returns:
The response from the broadcast.
"""
request = BroadcastTxRequest(
tx_bytes=transaction.SerializeToString(), mode=mode
)
return service_pb2_grpc.ServiceStub(self.channel).BroadcastTx(request)
async def simulate(self, transaction: Tx):
"""
Simulates a transaction.
Args:
transaction (Tx): The transaction to simulate.
Returns:
The response from the simulation.
"""
request = SimulateRequest(tx=transaction)
return service_pb2_grpc.ServiceStub(self.channel).Simulate(request)
async def send(
self, wallet: Wallet, transaction: Tx, mode=BroadcastMode.BROADCAST_MODE_SYNC
):
"""
Sends a transaction.
Args:
wallet (Wallet): The wallet to use for signing the transaction.
transaction (Tx): The transaction to send.
mode (BroadcastMode, optional): The broadcast mode. Defaults to BroadcastMode.BROADCAST_MODE_SYNC.
Returns:
The response from the broadcast.
"""
builder = self.builder
simulated = await self.simulate(transaction)
fee = self.builder.calculate_fee(simulated.gas_info.gas_used)
transaction = builder.build_transaction(wallet, transaction.body.messages, fee)
return await self.broadcast(transaction, mode)
async def send_message(
self, wallet: Wallet, message: Message, mode=BroadcastMode.BROADCAST_MODE_SYNC
):
"""
Sends a message.
Args:
wallet (Wallet): The wallet to use for signing the transaction.
message (Message): The message to send.
mode (BroadcastMode, optional): The broadcast mode. Defaults to BroadcastMode.BROADCAST_MODE_SYNC.
Returns:
The response from the broadcast.
"""
if self.sequence_manager:
await self.sequence_manager.before_send(wallet)
response = await self.send(wallet, self.builder.build(wallet, message), mode)
if self.sequence_manager:
await self.sequence_manager.after_send(wallet)
return response
async def broadcast_message(
self,
wallet: Wallet,
message: Message,
mode=BroadcastMode.BROADCAST_MODE_SYNC,
tx_options: Optional[TxOptions] = None,
):
"""
Broadcasts a message.
Args:
wallet (Wallet): The wallet to use for signing the transaction.
message (Message): The message to broadcast.
mode (BroadcastMode, optional): The broadcast mode. Defaults to BroadcastMode.BROADCAST_MODE_SYNC.
tx_options (TxOptions, optional): Options for transaction to support authenticators.
Returns:
The response from the broadcast.
"""
if not tx_options and self.sequence_manager:
await self.sequence_manager.before_send(wallet)
response = await self.broadcast(
self.builder.build(wallet, message, tx_options=tx_options),
mode,
)
if not tx_options and self.sequence_manager:
await self.sequence_manager.after_send(wallet)
return response
def build_transaction(self, wallet: Wallet, messages: List[Message], fee: Fee):
"""
Builds a transaction.
Args:
wallet (Wallet): The wallet to use for signing the transaction.
messages (List[Message]): The list of messages to include in the transaction.
fee (Fee): The fee to use for the transaction.
Returns:
The built transaction.
"""
return self.builder.build_transaction(wallet, messages, fee.as_proto())
def build(self, wallet: Wallet, message: Message, fee: Fee):
"""
Builds a transaction with a single message.
Args:
wallet (Wallet): The wallet to use for signing the transaction.
message (Message): The message to include in the transaction.
fee (Fee): The fee to use for the transaction.
Returns:
The built transaction.
"""
return self.builder.build(wallet, message, fee.as_proto())
def calculate_fee(self, gas_used) -> Fee:
"""
Calculates the fee based on the gas used.
Args:
gas_used: The amount of gas used.
Returns:
Fee: The calculated fee.
"""
gas_limit, amount = calculate_fee(gas_used, Denom(self.builder.denomination))
return Fee(gas_limit, [Coin(amount, self.builder.denomination)])
@dataclass
class NodeClient(MutatingNodeClient):
manage_sequence: bool = True
@staticmethod
async def connect(config: NodeConfig) -> Self:
client = NodeClient(config.channel, Builder(config.chain_id, config.usdc_denom))
if client.manage_sequence:
client.sequence_manager = SequenceManager(QueryNodeClient(client.channel))
return client
async def deposit(
self,
wallet: Wallet,
sender: str,
recipient_subaccount: SubaccountId,
asset_id: int,
quantums: int,
):
"""
Deposits funds into a subaccount.
Args:
wallet (Wallet): The wallet to use for signing the transaction.
sender (str): The sender address.
recipient_subaccount (SubaccountId): The recipient subaccount ID.
asset_id (int): The asset ID.
quantums (int): The amount of quantums to deposit.
Returns:
The response from the transaction broadcast.
"""
return await self.send_message(
wallet, deposit(sender, recipient_subaccount, asset_id, quantums)
)
async def withdraw(
self,
wallet: Wallet,
sender_subaccount: SubaccountId,
recipient: str,
asset_id: int,
quantums: int,
):
"""
Withdraws funds from a subaccount.
Args:
wallet (Wallet): The wallet to use for signing the transaction.
sender_subaccount (SubaccountId): The sender subaccount ID.
recipient (str): The recipient address.
asset_id (int): The asset ID.
quantums (int): The amount of quantums to withdraw.
Returns:
The response from the transaction broadcast.
"""
return await self.send_message(
wallet, withdraw(sender_subaccount, recipient, asset_id, quantums)
)
async def send_token(
self,
wallet: Wallet,
sender: str,
recipient: str,
quantums: int,
denomination: str,
):
"""
Sends tokens from one address to another.
Args:
wallet (Wallet): The wallet to use for signing the transaction.
sender (str): The sender address.
recipient (str): The recipient address.
quantums (int): The amount of quantums to send.
denomination (str): The denomination of the token.
Returns:
The response from the transaction broadcast.
"""
return await self.send_message(
wallet, send_token(sender, recipient, quantums, denomination)
)
async def transfer(
self,
wallet: Wallet,
sender_subaccount: SubaccountId,
recipient_subaccount: SubaccountId,
asset_id: int,
amount: int,
):
"""
Transfers funds between subaccounts.
Args:
wallet (Wallet): The wallet to use for signing the transaction.