dydx 0.3.0

dYdX v4 asynchronous client.
Documentation
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
use super::{Address, NodeClient};
use crate::indexer::{Denom, Height, Subaccount};
use anyhow::{anyhow as err, Error};
use dydx_proto::{
    cosmos::base::query::v1beta1::PageRequest as V4PageRequest,
    cosmos_sdk_proto::cosmos::{
        auth::v1beta1::{BaseAccount, QueryAccountRequest},
        bank::v1beta1::{QueryAllBalancesRequest, QueryBalanceRequest},
        base::{
            query::v1beta1::PageRequest as CosmosPageRequest,
            tendermint::v1beta1::{
                Block, GetLatestBlockRequest, GetNodeInfoRequest, GetNodeInfoResponse,
            },
            v1beta1::Coin,
        },
        staking::v1beta1::{
            DelegationResponse, QueryDelegatorDelegationsRequest,
            QueryDelegatorUnbondingDelegationsRequest, QueryValidatorsRequest, UnbondingDelegation,
            Validator,
        },
    },
    dydxprotocol::{
        accountplus::{AccountState, AccountStateRequest},
        blocktime::{QuerySynchronyParamsRequest, SynchronyParams},
        bridge::{DelayedCompleteBridgeMessage, QueryDelayedCompleteBridgeMessagesRequest},
        clob::{
            ClobPair, EquityTierLimitConfiguration, QueryAllClobPairRequest,
            QueryEquityTierLimitConfigurationRequest, QueryGetClobPairRequest,
            QueryNextClobPairIdRequest,
        },
        feetiers::{PerpetualFeeTier, QueryPerpetualFeeParamsRequest, QueryUserFeeTierRequest},
        perpetuals::{
            Perpetual, QueryAllPerpetualsRequest, QueryNextPerpetualIdRequest,
            QueryPerpetualRequest,
        },
        prices::{
            MarketPrice, QueryAllMarketPricesRequest, QueryMarketPriceRequest,
            QueryNextMarketIdRequest,
        },
        ratelimit::{LimiterCapacity, QueryCapacityByDenomRequest},
        revshare::{OrderRouterRevShare, QueryOrderRouterRevShare},
        rewards,
        stats::{QueryUserStatsRequest, UserStats},
        subaccounts::{
            QueryAllSubaccountRequest, QueryGetSubaccountRequest, Subaccount as SubaccountInfo,
        },
    },
};

impl NodeClient {
    /// Query for [account balances](https://github.com/cosmos/cosmos-sdk/tree/main/x/bank#allbalances)
    /// by address for all denominations.
    ///
    /// Check [the example](https://github.com/dydxprotocol/v4-clients/blob/main/v4-client-rs/client/examples/validator_get.rs).
    pub async fn get_account_balances(&mut self, address: &Address) -> Result<Vec<Coin>, Error> {
        let req = QueryAllBalancesRequest {
            address: address.to_string(),
            resolve_denom: false,
            pagination: None,
        };
        let balances = self.bank.all_balances(req).await?.into_inner().balances;
        Ok(balances)
    }

    /// Query for account [balance](https://github.com/cosmos/cosmos-sdk/tree/main/x/bank#balance)
    /// by address for a given denomination.
    ///
    /// Check [the example](https://github.com/dydxprotocol/v4-clients/blob/main/v4-client-rs/client/examples/validator_get.rs).
    pub async fn get_account_balance(
        &mut self,
        address: &Address,
        denom: &Denom,
    ) -> Result<Coin, Error> {
        let req = QueryBalanceRequest {
            address: address.to_string(),
            denom: denom.to_string(),
        };
        let balance = self
            .bank
            .balance(req)
            .await?
            .into_inner()
            .balance
            .ok_or_else(|| err!("Balance query response does not contain balance"))?;
        Ok(balance)
    }

    /// Query for [an account](https://github.com/cosmos/cosmos-sdk/tree/main/x/auth#account-1)
    /// by it's address.
    ///
    /// Check [the example](https://github.com/dydxprotocol/v4-clients/blob/main/v4-client-rs/client/examples/validator_get.rs).
    pub async fn get_account(&mut self, address: &Address) -> Result<BaseAccount, Error> {
        let req = QueryAccountRequest {
            address: address.to_string(),
        };
        let resp = self
            .auth
            .account(req)
            .await?
            .into_inner()
            .account
            .ok_or_else(|| err!("Query account request failure, account should exist."))?
            .to_msg()?;
        Ok(resp)
    }

    /// Query for node info.
    ///
    /// Check [the example](https://github.com/dydxprotocol/v4-clients/blob/main/v4-client-rs/client/examples/validator_get.rs).
    pub async fn get_node_info(&mut self) -> Result<GetNodeInfoResponse, Error> {
        let req = GetNodeInfoRequest {};
        let info = self.base.get_node_info(req).await?.into_inner();
        Ok(info)
    }

    /// Query for the latest block.
    ///
    /// Check [the example](https://github.com/dydxprotocol/v4-clients/blob/main/v4-client-rs/client/examples/validator_get.rs).
    #[deprecated(since = "0.3.0", note = "Use `latest_block` instead")]
    pub async fn get_latest_block(&mut self) -> Result<Block, Error> {
        self.latest_block().await
    }

    /// Query for the latest block.
    ///
    /// Check [the example](https://github.com/dydxprotocol/v4-clients/blob/main/v4-client-rs/client/examples/validator_get.rs).
    pub async fn latest_block(&mut self) -> Result<Block, Error> {
        let req = GetLatestBlockRequest::default();
        let latest_block = self
            .base
            .get_latest_block(req)
            .await?
            .into_inner()
            .sdk_block
            .ok_or_else(|| err!("The latest block is empty"))?;
        Ok(latest_block)
    }

    /// Query for the latest block height.
    ///
    /// Check [the example](https://github.com/dydxprotocol/v4-clients/blob/main/v4-client-rs/client/examples/validator_get.rs).
    #[deprecated(since = "0.3.0", note = "Use `latest_block_height` instead")]
    pub async fn get_latest_block_height(&mut self) -> Result<Height, Error> {
        self.latest_block_height().await
    }

    /// Query for the latest block height.
    ///
    /// Check [the example](https://github.com/dydxprotocol/v4-clients/blob/main/v4-client-rs/client/examples/validator_get.rs).
    pub async fn latest_block_height(&mut self) -> Result<Height, Error> {
        let latest_block = self.latest_block().await?;
        let header = latest_block
            .header
            .ok_or_else(|| err!("The block doesn't contain a header"))?;
        let height = Height(header.height.try_into()?);
        Ok(height)
    }

    /// Query for user stats (Maker and Taker positions).
    ///
    /// Check [the example](https://github.com/dydxprotocol/v4-clients/blob/main/v4-client-rs/client/examples/validator_get.rs).
    pub async fn get_user_stats(&mut self, address: &Address) -> Result<UserStats, Error> {
        let req = QueryUserStatsRequest {
            user: address.to_string(),
        };
        let stats = self
            .stats
            .user_stats(req)
            .await?
            .into_inner()
            .stats
            .ok_or_else(|| err!("User stats query response does not contain stats"))?;
        Ok(stats)
    }

    /// Query for [all validators](https://github.com/cosmos/cosmos-sdk/tree/main/x/staking#validators-2)
    /// that match the given status.
    ///
    /// Check [the example](https://github.com/dydxprotocol/v4-clients/blob/main/v4-client-rs/client/examples/validator_get.rs).
    pub async fn get_all_validators(
        &mut self,
        status: Option<String>,
    ) -> Result<Vec<Validator>, Error> {
        let req = QueryValidatorsRequest {
            status: status.unwrap_or_default(),
            pagination: None,
        };
        let validators = self.staking.validators(req).await?.into_inner().validators;
        Ok(validators)
    }

    /// Query for all subacccounts.
    ///
    /// Check [the example](https://github.com/dydxprotocol/v4-clients/blob/main/v4-client-rs/client/examples/validator_get.rs).
    pub async fn get_subaccounts(&mut self) -> Result<Vec<SubaccountInfo>, Error> {
        let req = QueryAllSubaccountRequest { pagination: None };
        let subaccounts = self
            .subaccounts
            .subaccount_all(req)
            .await?
            .into_inner()
            .subaccount;
        Ok(subaccounts)
    }

    /// Query for the subacccount.
    ///
    /// Check [the example](https://github.com/dydxprotocol/v4-clients/blob/main/v4-client-rs/client/examples/validator_get.rs).
    pub async fn get_subaccount(
        &mut self,
        subaccount: &Subaccount,
    ) -> Result<SubaccountInfo, Error> {
        let req = QueryGetSubaccountRequest {
            owner: subaccount.address.to_string(),
            number: subaccount.number.0,
        };
        let subaccount = self
            .subaccounts
            .subaccount(req)
            .await?
            .into_inner()
            .subaccount
            .ok_or_else(|| err!("Subaccount query response does not contain subaccount info"))?;
        Ok(subaccount)
    }

    /// Query for the orderbook pair by its id.
    ///
    /// Check [the example](https://github.com/dydxprotocol/v4-clients/blob/main/v4-client-rs/client/examples/validator_get.rs).
    pub async fn get_clob_pair(&mut self, pair_id: u32) -> Result<ClobPair, Error> {
        let req = QueryGetClobPairRequest { id: pair_id };
        let clob_pair = self
            .clob
            .clob_pair(req)
            .await?
            .into_inner()
            .clob_pair
            .ok_or_else(|| err!("Clob pair {pair_id} query response does not contain clob pair"))?;
        Ok(clob_pair)
    }

    /// Query for all orderbook pairs.
    ///
    /// Check [the example](https://github.com/dydxprotocol/v4-clients/blob/main/v4-client-rs/client/examples/validator_get.rs).
    pub async fn get_clob_pairs(
        &mut self,
        pagination: Option<V4PageRequest>,
    ) -> Result<Vec<ClobPair>, Error> {
        let req = QueryAllClobPairRequest { pagination };
        let clob_pairs = self.clob.clob_pair_all(req).await?.into_inner().clob_pair;
        Ok(clob_pairs)
    }

    /// Query for the market price.
    ///
    /// Check [the example](https://github.com/dydxprotocol/v4-clients/blob/main/v4-client-rs/client/examples/validator_get.rs).
    pub async fn get_price(&mut self, market_id: u32) -> Result<MarketPrice, Error> {
        let req = QueryMarketPriceRequest { id: market_id };
        let price = self
            .prices
            .market_price(req)
            .await?
            .into_inner()
            .market_price
            .ok_or_else(|| {
                err!("Market {market_id} price query response does not contain price")
            })?;
        Ok(price)
    }

    /// Query for all markets prices.
    ///
    /// Check [the example](https://github.com/dydxprotocol/v4-clients/blob/main/v4-client-rs/client/examples/validator_get.rs).
    pub async fn get_prices(
        &mut self,
        pagination: Option<V4PageRequest>,
    ) -> Result<Vec<MarketPrice>, Error> {
        let req = QueryAllMarketPricesRequest { pagination };
        let prices = self
            .prices
            .all_market_prices(req)
            .await?
            .into_inner()
            .market_prices;
        Ok(prices)
    }

    /// Query for the perpetual.
    ///
    /// Check [the example](https://github.com/dydxprotocol/v4-clients/blob/main/v4-client-rs/client/examples/validator_get.rs).
    pub async fn get_perpetual(&mut self, perpetual_id: u32) -> Result<Perpetual, Error> {
        let req = QueryPerpetualRequest { id: perpetual_id };
        let perpetual = self
            .perpetuals
            .perpetual(req)
            .await?
            .into_inner()
            .perpetual
            .ok_or_else(|| {
                err!("Perpetual {perpetual_id} query response does not contain perpetual")
            })?;
        Ok(perpetual)
    }

    /// Query for all perpetuals.
    ///
    /// Check [the example](https://github.com/dydxprotocol/v4-clients/blob/main/v4-client-rs/client/examples/validator_get.rs).
    pub async fn get_perpetuals(
        &mut self,
        pagination: Option<V4PageRequest>,
    ) -> Result<Vec<Perpetual>, Error> {
        let req = QueryAllPerpetualsRequest { pagination };
        let perpetuals = self
            .perpetuals
            .all_perpetuals(req)
            .await?
            .into_inner()
            .perpetual;
        Ok(perpetuals)
    }

    /// Query for [`EquityTierLimitConfiguration`].
    ///
    /// Check [the example](https://github.com/dydxprotocol/v4-clients/blob/main/v4-client-rs/client/examples/validator_get.rs).
    #[deprecated(
        since = "0.3.0",
        note = "Use `get_equity_tier_limit_configuration` instead"
    )]
    pub async fn get_equity_tier_limit_config(
        &mut self,
    ) -> Result<EquityTierLimitConfiguration, Error> {
        self.get_equity_tier_limit_configuration().await
    }

    /// Query for [`EquityTierLimitConfiguration`].
    ///
    /// Check [the example](https://github.com/dydxprotocol/v4-clients/blob/main/v4-client-rs/client/examples/validator_get.rs).
    pub async fn get_equity_tier_limit_configuration(
        &mut self,
    ) -> Result<EquityTierLimitConfiguration, Error> {
        let req = QueryEquityTierLimitConfigurationRequest {};
        let etlc = self
            .clob
            .equity_tier_limit_configuration(req)
            .await?
            .into_inner()
            .equity_tier_limit_config
            .ok_or_else(|| {
                err!("Equity tier limit config query response does not contain config")
            })?;
        Ok(etlc)
    }

    /// Query for [all delegations](https://github.com/cosmos/cosmos-sdk/tree/main/x/staking#delegatordelegations)
    /// of a given delegator address.
    ///
    /// Check [the example](https://github.com/dydxprotocol/v4-clients/blob/main/v4-client-rs/client/examples/validator_get.rs).
    pub async fn get_delegator_delegations(
        &mut self,
        delegator_address: Address,
        pagination: Option<CosmosPageRequest>,
    ) -> Result<Vec<DelegationResponse>, Error> {
        let req = QueryDelegatorDelegationsRequest {
            delegator_addr: delegator_address.to_string(),
            pagination,
        };
        let delegations = self
            .staking
            .delegator_delegations(req)
            .await?
            .into_inner()
            .delegation_responses;
        Ok(delegations)
    }

    /// Query for [all unbonding delegations](https://github.com/cosmos/cosmos-sdk/tree/main/x/staking#delegatorunbondingdelegations)
    /// of a given delegator address.
    ///
    /// Check [the example](https://github.com/dydxprotocol/v4-clients/blob/main/v4-client-rs/client/examples/validator_get.rs).
    pub async fn get_delegator_unbonding_delegations(
        &mut self,
        delegator_address: Address,
        pagination: Option<CosmosPageRequest>,
    ) -> Result<Vec<UnbondingDelegation>, Error> {
        let req = QueryDelegatorUnbondingDelegationsRequest {
            delegator_addr: delegator_address.to_string(),
            pagination,
        };
        let responses = self
            .staking
            .delegator_unbonding_delegations(req)
            .await?
            .into_inner()
            .unbonding_responses;
        Ok(responses)
    }

    /// Query for delayed bridge messages for the address.
    ///
    /// Check [the example](https://github.com/dydxprotocol/v4-clients/blob/main/v4-client-rs/client/examples/validator_get.rs).
    pub async fn get_delayed_complete_bridge_messages(
        &mut self,
        address: Address,
    ) -> Result<Vec<DelayedCompleteBridgeMessage>, Error> {
        let req = QueryDelayedCompleteBridgeMessagesRequest {
            address: address.to_string(),
        };
        let messages = self
            .bridge
            .delayed_complete_bridge_messages(req)
            .await?
            .into_inner()
            .messages;
        Ok(messages)
    }

    /// Query for fee tiers for perpetuals.
    ///
    /// Check [the example](https://github.com/dydxprotocol/v4-clients/blob/main/v4-client-rs/client/examples/validator_get.rs).
    pub async fn get_fee_tiers(&mut self) -> Result<Vec<PerpetualFeeTier>, Error> {
        let req = QueryPerpetualFeeParamsRequest {};
        let tiers = self
            .feetiers
            .perpetual_fee_params(req)
            .await?
            .into_inner()
            .params
            .ok_or_else(|| err!("Fee tiers query response does not contain params"))?
            .tiers;
        Ok(tiers)
    }

    /// Query for perpetual fee tier for the address.
    ///
    /// Check [the example](https://github.com/dydxprotocol/v4-clients/blob/main/v4-client-rs/client/examples/validator_get.rs).
    pub async fn get_user_fee_tier(&mut self, address: Address) -> Result<PerpetualFeeTier, Error> {
        let req = QueryUserFeeTierRequest {
            user: address.to_string(),
        };
        let tier = self
            .feetiers
            .user_fee_tier(req)
            .await?
            .into_inner()
            .tier
            .ok_or_else(|| err!("User fee tier query response does not contain tier"))?;
        Ok(tier)
    }

    /// Query for rewards params.
    ///
    /// Check [the example](https://github.com/dydxprotocol/v4-clients/blob/main/v4-client-rs/client/examples/validator_get.rs).
    pub async fn get_rewards_params(&mut self) -> Result<rewards::Params, Error> {
        let req = rewards::QueryParamsRequest {};
        let params = self
            .rewards
            .params(req)
            .await?
            .into_inner()
            .params
            .ok_or_else(|| err!("Rewards query response does not contain params"))?;
        Ok(params)
    }

    /// Query capacity by denom.
    ///
    /// Check [the example](https://github.com/dydxprotocol/v4-clients/blob/main/v4-client-rs/client/examples/validator_get.rs).
    pub async fn get_withdrawal_capacity_by_denom(
        &mut self,
        denom: Denom,
    ) -> Result<Vec<LimiterCapacity>, Error> {
        let req = QueryCapacityByDenomRequest {
            denom: denom.to_string(),
        };
        let capacity = self
            .ratelimit
            .capacity_by_denom(req)
            .await?
            .into_inner()
            .limiter_capacity_list;

        Ok(capacity)
    }

    /// Queries for an account state (timestamp nonce).
    pub async fn get_account_state(&mut self, address: &Address) -> Result<AccountState, Error> {
        let req = AccountStateRequest {
            address: address.to_string(),
        };

        let state = self
            .accountplus
            .account_state(req)
            .await?
            .into_inner()
            .account_state
            .ok_or_else(|| err!("Account state query response does not contain account state"))?;

        Ok(state)
    }

    /// Queries for synchrony params.
    pub async fn get_synchrony_params(&mut self) -> Result<SynchronyParams, Error> {
        let req = QuerySynchronyParamsRequest {};

        let params = self
            .blocktime
            .synchrony_params(req)
            .await?
            .into_inner()
            .params
            .ok_or_else(|| err!("Synchrony params query response does not contain params"))?;

        Ok(params)
    }

    /// Queries for the next CLOB pair ID.
    pub async fn get_next_clob_pair_id(&mut self) -> Result<u32, Error> {
        let req = QueryNextClobPairIdRequest {};

        let id = self
            .clob
            .next_clob_pair_id(req)
            .await?
            .into_inner()
            .next_clob_pair_id;

        Ok(id)
    }

    /// Queries for the next perpetual ID.
    pub async fn get_next_perpetual_id(&mut self) -> Result<u32, Error> {
        let req = QueryNextPerpetualIdRequest {};

        let id = self
            .perpetuals
            .next_perpetual_id(req)
            .await?
            .into_inner()
            .next_perpetual_id;

        Ok(id)
    }

    /// Queries for the next market ID.
    pub async fn get_next_market_id(&mut self) -> Result<u32, Error> {
        let req = QueryNextMarketIdRequest {};

        let id = self
            .prices
            .next_market_id(req)
            .await?
            .into_inner()
            .next_market_id;

        Ok(id)
    }

    /// Queries for the order router rev share.
    pub async fn get_order_router_rev_share(
        &mut self,
        address: Address,
    ) -> Result<OrderRouterRevShare, Error> {
        let req = QueryOrderRouterRevShare {
            address: address.to_string(),
        };

        let rev_share = self
            .revshare
            .order_router_rev_share(req)
            .await?
            .into_inner()
            .order_router_rev_share
            .ok_or_else(|| {
                err!("Order router rev share query response does not contain rev share")
            })?;

        Ok(rev_share)
    }
}