hyli-client-sdk 0.14.0

Hyli client SDK
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
581
582
583
584
585
586
587
use std::{
    future::Future,
    ops::{Deref, DerefMut},
    pin::Pin,
    time::Duration,
};

use anyhow::{Context, Result};
use hyli_net::http::HttpClient;
use sdk::{
    api::{
        APIBlob, APIBlock, APIContract, APINodeContract, APIRegisterContract, APIStaking,
        APITransaction, NodeInfo, TransactionStatusDb, TransactionWithBlobs,
    },
    BlobIndex, BlobTransaction, BlockHash, BlockHeight, ConsensusInfo, Contract, ContractName,
    ProofTransaction, TxHash, TxId, UnsettledBlobTransaction, ValidatorPublicKey,
};

#[derive(Clone)]
pub struct IndexerApiHttpClient {
    pub client: HttpClient,
}

impl IndexerApiHttpClient {
    pub fn new(url: String) -> Result<Self> {
        Ok(IndexerApiHttpClient {
            client: HttpClient {
                url: url.parse()?,
                api_key: None,
                retry: None,
            },
        })
    }

    #[cfg_attr(feature = "instrumentation", tracing::instrument(skip(self)))]
    pub async fn list_contracts(&self) -> Result<Vec<APIContract>> {
        self.get("v1/indexer/contracts")
            .await
            .context("listing contracts")
    }

    #[cfg_attr(feature = "instrumentation", tracing::instrument(skip(self)))]
    pub async fn get_indexer_contract(&self, contract_name: &ContractName) -> Result<APIContract> {
        self.get(&format!("v1/indexer/contract/{contract_name}"))
            .await
            .context(format!("getting contract {contract_name}"))
    }

    #[cfg_attr(feature = "instrumentation", tracing::instrument(skip(self)))]
    pub async fn fetch_current_state<State>(&self, contract_name: &ContractName) -> Result<State>
    where
        State: serde::de::DeserializeOwned,
    {
        self.get::<State>(&format!("v1/indexer/contract/{contract_name}/state"))
            .await
            .context(format!("getting contract {contract_name} state"))
    }

    #[cfg_attr(feature = "instrumentation", tracing::instrument(skip(self)))]
    pub async fn get_block_height(&self) -> Result<BlockHeight> {
        let block: APIBlock = self.get_last_block().await?;
        Ok(BlockHeight(block.height))
    }

    #[cfg_attr(feature = "instrumentation", tracing::instrument(skip(self)))]
    pub async fn get_blocks(&self) -> Result<Vec<APIBlock>> {
        self.get("v1/indexer/blocks")
            .await
            .context("getting blocks")
    }

    #[cfg_attr(feature = "instrumentation", tracing::instrument(skip(self)))]
    pub async fn get_last_block(&self) -> Result<APIBlock> {
        self.get("v1/indexer/block/last")
            .await
            .context("getting last block")
    }

    #[cfg_attr(feature = "instrumentation", tracing::instrument(skip(self)))]
    pub async fn get_block_by_height(&self, height: &BlockHeight) -> Result<APIBlock> {
        self.get(&format!("v1/indexer/block/height/{height}"))
            .await
            .context(format!("getting block with height {height}"))
    }

    #[cfg_attr(feature = "instrumentation", tracing::instrument(skip(self)))]
    pub async fn get_block_by_hash(&self, hash: &BlockHash) -> Result<APIBlock> {
        self.get(&format!("v1/indexer/block/hash/{hash}"))
            .await
            .context(format!("getting block with hash {hash}"))
    }

    #[cfg_attr(feature = "instrumentation", tracing::instrument(skip(self)))]
    pub async fn get_transactions(&self) -> Result<Vec<APITransaction>> {
        self.get("v1/indexer/transactions")
            .await
            .context("getting transactions")
    }

    #[cfg_attr(feature = "instrumentation", tracing::instrument(skip(self)))]
    pub async fn get_transactions_by_height(
        &self,
        height: &BlockHeight,
    ) -> Result<Vec<APITransaction>> {
        self.get(&format!("v1/indexer/transactions/block/{height}"))
            .await
            .context(format!("getting transactions for block height {height}"))
    }

    #[cfg_attr(feature = "instrumentation", tracing::instrument(skip(self)))]
    pub async fn get_transactions_by_contract(
        &self,
        contract_name: &ContractName,
    ) -> Result<Vec<APITransaction>> {
        self.get(&format!("v1/indexer/transactions/contract/{contract_name}"))
            .await
            .context(format!("getting transactions for contract {contract_name}"))
    }

    /// Get the last settled tx id by contract name and status
    /// If status is not provided, it will return the last settled tx id for all statuses (success, failure, timed_out)
    #[cfg_attr(feature = "instrumentation", tracing::instrument(skip(self)))]
    pub async fn get_last_settled_txid_by_contract(
        &self,
        contract_name: &ContractName,
        status: Option<Vec<TransactionStatusDb>>,
    ) -> Result<Option<TxId>> {
        self.get(&format!(
            "v1/indexer/transactions/contract/{contract_name}/last_settled_tx_id?status={}",
            status
                .map(|s| s
                    .into_iter()
                    .map(|s| s.to_string())
                    .collect::<Vec<String>>()
                    .join(","))
                .unwrap_or_default(),
        ))
        .await
        .context(format!(
            "getting last settled tx by contract {contract_name}"
        ))
    }

    #[cfg_attr(feature = "instrumentation", tracing::instrument(skip(self)))]
    pub async fn get_transaction_with_hash(&self, tx_hash: &TxHash) -> Result<APITransaction> {
        self.get(&format!("v1/indexer/transaction/hash/{tx_hash}"))
            .await
            .context(format!("getting transaction with hash {tx_hash}"))
    }

    #[cfg_attr(feature = "instrumentation", tracing::instrument(skip(self)))]
    pub async fn get_blob_transactions_by_contract(
        &self,
        contract_name: &ContractName,
    ) -> Result<Vec<TransactionWithBlobs>> {
        self.get(&format!(
            "v1/indexer/blob_transactions/contract/{contract_name}"
        ))
        .await
        .context(format!(
            "getting blob transactions for contract {contract_name}"
        ))
    }

    #[cfg_attr(feature = "instrumentation", tracing::instrument(skip(self)))]
    pub async fn get_blobs_by_tx_hash(&self, tx_hash: &TxHash) -> Result<Vec<APIBlob>> {
        self.get(&format!("v1/indexer/blobs/hash/{tx_hash}"))
            .await
            .context(format!("getting blob by transaction hash {tx_hash}"))
    }

    #[cfg_attr(feature = "instrumentation", tracing::instrument(skip(self)))]
    pub async fn get_blob(&self, tx_hash: &TxHash, blob_index: BlobIndex) -> Result<APIBlob> {
        self.get(&format!(
            "v1/indexer/blob/hash/{tx_hash}/index/{blob_index}"
        ))
        .await
        .context(format!(
            "getting blob with hash {tx_hash} and index {blob_index}"
        ))
    }
}

impl Deref for IndexerApiHttpClient {
    type Target = HttpClient;

    fn deref(&self) -> &Self::Target {
        &self.client
    }
}

#[derive(Clone)]
pub struct NodeApiHttpClient {
    pub client: HttpClient,
}

pub trait NodeApiClient {
    fn register_contract(
        &self,
        tx: APIRegisterContract,
    ) -> Pin<Box<dyn Future<Output = Result<TxHash>> + Send + '_>>;

    fn send_tx_blob(
        &self,
        tx: BlobTransaction,
    ) -> Pin<Box<dyn Future<Output = Result<TxHash>> + Send + '_>>;

    fn send_tx_proof(
        &self,
        tx: ProofTransaction,
    ) -> Pin<Box<dyn Future<Output = Result<TxHash>> + Send + '_>>;

    fn get_consensus_info(
        &self,
    ) -> Pin<Box<dyn Future<Output = Result<ConsensusInfo>> + Send + '_>>;

    fn get_consensus_staking_state(
        &self,
    ) -> Pin<Box<dyn Future<Output = Result<APIStaking>> + Send + '_>>;

    fn get_node_info(&self) -> Pin<Box<dyn Future<Output = Result<NodeInfo>> + Send + '_>>;

    fn metrics(&self) -> Pin<Box<dyn Future<Output = Result<String>> + Send + '_>>;

    fn get_block_height(&self) -> Pin<Box<dyn Future<Output = Result<BlockHeight>> + Send + '_>>;

    fn get_contract(
        &self,
        contract_name: ContractName,
    ) -> Pin<Box<dyn Future<Output = Result<APINodeContract>> + Send + '_>>;

    fn get_settled_height(
        &self,
        contract_name: ContractName,
    ) -> Pin<Box<dyn Future<Output = Result<BlockHeight>> + Send + '_>>;

    fn get_unsettled_tx(
        &self,
        blob_tx_hash: TxHash,
    ) -> Pin<Box<dyn Future<Output = Result<UnsettledBlobTransaction>> + Send + '_>>;
}

impl NodeApiHttpClient {
    pub fn new(url: String) -> Result<Self> {
        Ok(NodeApiHttpClient {
            client: HttpClient {
                url: url.parse()?,
                api_key: None,
                retry: None,
            },
        })
    }

    /// Create a new client with a retry configuration (retrying `n` times, waiting `duration` before each retry)
    #[allow(dead_code)]
    pub fn with_retry(&self, n: usize, duration: Duration) -> Self {
        let mut cloned = self.clone();
        cloned.retry = Some((n, duration));
        cloned
    }

    /// Create a client with the retry configuration (n=3, duration=1000ms)
    #[allow(dead_code)]
    pub fn retry_15times_1000ms(&self) -> Self {
        self.with_retry(8, Duration::from_millis(4000))
    }
}

impl NodeApiClient for NodeApiHttpClient {
    #[cfg_attr(feature = "instrumentation", tracing::instrument(skip(self)))]
    fn register_contract(
        &self,
        tx: APIRegisterContract,
    ) -> Pin<Box<dyn Future<Output = Result<TxHash>> + Send + '_>> {
        Box::pin(async move {
            self.post_json("v1/contract/register", &tx)
                .await
                .context("Registering contract")
        })
    }

    #[cfg_attr(feature = "instrumentation", tracing::instrument(skip(self)))]
    fn send_tx_blob(
        &self,
        tx: BlobTransaction,
    ) -> Pin<Box<dyn Future<Output = Result<TxHash>> + Send + '_>> {
        Box::pin(async move {
            self.post_json("v1/tx/send/blob", &tx)
                .await
                .context("Sending tx blob")
        })
    }

    #[cfg_attr(feature = "instrumentation", tracing::instrument(skip(self)))]
    fn send_tx_proof(
        &self,
        tx: ProofTransaction,
    ) -> Pin<Box<dyn Future<Output = Result<TxHash>> + Send + '_>> {
        Box::pin(async move {
            self.post_json("v1/tx/send/proof", &tx)
                .await
                .context("Sending tx proof")
        })
    }

    #[cfg_attr(feature = "instrumentation", tracing::instrument(skip(self)))]
    fn get_consensus_info(
        &self,
    ) -> Pin<Box<dyn Future<Output = Result<ConsensusInfo>> + Send + '_>> {
        Box::pin(async move {
            self.get("v1/consensus/info")
                .await
                .context("getting consensus info")
        })
    }

    #[cfg_attr(feature = "instrumentation", tracing::instrument(skip(self)))]
    fn get_consensus_staking_state(
        &self,
    ) -> Pin<Box<dyn Future<Output = Result<APIStaking>> + Send + '_>> {
        Box::pin(async move {
            self.get("v1/consensus/staking_state")
                .await
                .context("getting consensus staking state")
        })
    }

    #[cfg_attr(feature = "instrumentation", tracing::instrument(skip(self)))]
    fn get_node_info(&self) -> Pin<Box<dyn Future<Output = Result<NodeInfo>> + Send + '_>> {
        Box::pin(async move { self.get("v1/info").await.context("getting node info") })
    }

    #[cfg_attr(feature = "instrumentation", tracing::instrument(skip(self)))]
    fn metrics(&self) -> Pin<Box<dyn Future<Output = Result<String>> + Send + '_>> {
        Box::pin(async move {
            self.get_str("v1/metrics")
                .await
                .context("getting node metrics")
        })
    }

    #[cfg_attr(feature = "instrumentation", tracing::instrument(skip(self)))]
    fn get_block_height(&self) -> Pin<Box<dyn Future<Output = Result<BlockHeight>> + Send + '_>> {
        Box::pin(async move {
            self.get("v1/da/block/height")
                .await
                .context("getting block height")
        })
    }

    #[cfg_attr(feature = "instrumentation", tracing::instrument(skip(self)))]
    fn get_contract(
        &self,
        contract_name: ContractName,
    ) -> Pin<Box<dyn Future<Output = Result<APINodeContract>> + Send + '_>> {
        Box::pin(async move {
            self.get(&format!("v1/contract/{contract_name}"))
                .await
                .context(format!("getting contract {contract_name}"))
        })
    }

    #[cfg_attr(feature = "instrumentation", tracing::instrument(skip(self)))]
    fn get_unsettled_tx(
        &self,
        blob_tx_hash: TxHash,
    ) -> Pin<Box<dyn Future<Output = Result<UnsettledBlobTransaction>> + Send + '_>> {
        Box::pin(async move {
            self.get(&format!("v1/unsettled_tx/{blob_tx_hash}"))
                .await
                .context(format!("getting tx {blob_tx_hash}"))
        })
    }

    #[cfg_attr(feature = "instrumentation", tracing::instrument(skip(self)))]
    fn get_settled_height(
        &self,
        contract_name: ContractName,
    ) -> Pin<Box<dyn Future<Output = Result<BlockHeight>> + Send + '_>> {
        Box::pin(async move {
            self.get(&format!("v1/contract/{contract_name}/settled_height"))
                .await
                .context(format!(
                    "getting earliest unsettled height for contract {contract_name}"
                ))
        })
    }
}

impl Deref for NodeApiHttpClient {
    type Target = HttpClient;

    fn deref(&self) -> &Self::Target {
        &self.client
    }
}
impl DerefMut for NodeApiHttpClient {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.client
    }
}

#[allow(dead_code)]
pub mod test {
    use sdk::{hyli_model_utils::TimestampMs, Hashed, TimeoutWindow};

    use super::*;
    use std::sync::{Arc, Mutex};

    #[derive(Clone)]
    pub struct NodeApiMockClient {
        pub block_height: Arc<Mutex<BlockHeight>>,
        pub settled_height: Arc<Mutex<BlockHeight>>,
        pub consensus_info: Arc<Mutex<ConsensusInfo>>,
        pub node_info: Arc<Mutex<NodeInfo>>,
        pub staking_state: Arc<Mutex<APIStaking>>,
        pub contracts: Arc<Mutex<std::collections::HashMap<ContractName, Contract>>>,
        pub unsettled_txs: Arc<Mutex<std::collections::HashMap<TxHash, UnsettledBlobTransaction>>>,
        pub pending_proofs: Arc<Mutex<Vec<ProofTransaction>>>,
        pub pending_blobs: Arc<Mutex<Vec<BlobTransaction>>>,
    }

    impl NodeApiMockClient {
        pub fn new() -> Self {
            Self {
                block_height: Arc::new(Mutex::new(BlockHeight(0))),
                settled_height: Arc::new(Mutex::new(BlockHeight(0))),
                consensus_info: Arc::new(Mutex::new(ConsensusInfo {
                    slot: 0,
                    view: 0,
                    round_leader: ValidatorPublicKey::default(),
                    last_timestamp: TimestampMs::default(),
                    validators: vec![],
                })),
                node_info: Arc::new(Mutex::new(NodeInfo {
                    id: "mock_node_id".to_string(),
                    pubkey: Some(ValidatorPublicKey::default()),
                    da_address: "mock_da_address".to_string(),
                })),
                staking_state: Arc::new(Mutex::new(APIStaking::default())),
                contracts: Arc::new(Mutex::new(std::collections::HashMap::new())),
                unsettled_txs: Arc::new(Mutex::new(std::collections::HashMap::new())),
                pending_proofs: Arc::new(Mutex::new(vec![])),
                pending_blobs: Arc::new(Mutex::new(vec![])),
            }
        }

        pub fn set_block_height(&self, height: BlockHeight) {
            *self.block_height.lock().unwrap() = height;
        }

        pub fn set_settled_height(&self, height: BlockHeight) {
            *self.settled_height.lock().unwrap() = height;
        }

        pub fn set_consensus_info(&self, info: ConsensusInfo) {
            *self.consensus_info.lock().unwrap() = info;
        }

        pub fn set_node_info(&self, info: NodeInfo) {
            *self.node_info.lock().unwrap() = info;
        }

        pub fn set_staking_state(&self, state: APIStaking) {
            *self.staking_state.lock().unwrap() = state;
        }

        pub fn add_contract(&self, contract: Contract) {
            self.contracts
                .lock()
                .unwrap()
                .insert(contract.name.clone(), contract);
        }

        pub fn add_unsettled_tx(&self, tx_hash: TxHash, tx: UnsettledBlobTransaction) {
            self.unsettled_txs.lock().unwrap().insert(tx_hash, tx);
        }
    }

    impl Default for NodeApiMockClient {
        fn default() -> Self {
            Self::new()
        }
    }

    impl NodeApiClient for NodeApiMockClient {
        fn register_contract(
            &self,
            tx: APIRegisterContract,
        ) -> Pin<Box<dyn Future<Output = Result<TxHash>> + Send + '_>> {
            Box::pin(async move { Ok(BlobTransaction::from(tx).hashed()) })
        }

        fn send_tx_blob(
            &self,
            tx: BlobTransaction,
        ) -> Pin<Box<dyn Future<Output = Result<TxHash>> + Send + '_>> {
            self.pending_blobs.lock().unwrap().push(tx.clone());
            Box::pin(async move { Ok(tx.hashed()) })
        }

        fn send_tx_proof(
            &self,
            tx: ProofTransaction,
        ) -> Pin<Box<dyn Future<Output = Result<TxHash>> + Send + '_>> {
            self.pending_proofs.lock().unwrap().push(tx.clone());
            Box::pin(async move { Ok(tx.hashed()) })
        }

        fn get_consensus_info(
            &self,
        ) -> Pin<Box<dyn Future<Output = Result<ConsensusInfo>> + Send + '_>> {
            Box::pin(async move { Ok(self.consensus_info.lock().unwrap().clone()) })
        }

        fn get_consensus_staking_state(
            &self,
        ) -> Pin<Box<dyn Future<Output = Result<APIStaking>> + Send + '_>> {
            Box::pin(async move { Ok(self.staking_state.lock().unwrap().clone()) })
        }

        fn get_node_info(&self) -> Pin<Box<dyn Future<Output = Result<NodeInfo>> + Send + '_>> {
            Box::pin(async move { Ok(self.node_info.lock().unwrap().clone()) })
        }

        fn metrics(&self) -> Pin<Box<dyn Future<Output = Result<String>> + Send + '_>> {
            Box::pin(async move { Ok("mock metrics".to_string()) })
        }

        fn get_block_height(
            &self,
        ) -> Pin<Box<dyn Future<Output = Result<BlockHeight>> + Send + '_>> {
            Box::pin(async move { Ok(*self.block_height.lock().unwrap()) })
        }

        fn get_contract(
            &self,
            contract_name: ContractName,
        ) -> Pin<Box<dyn Future<Output = Result<APINodeContract>> + Send + '_>> {
            Box::pin(async move {
                let contract = self
                    .contracts
                    .lock()
                    .unwrap()
                    .get(&contract_name)
                    .cloned()
                    .ok_or_else(|| anyhow::anyhow!("Contract not found"))?;
                let block_height = *self.block_height.lock().unwrap();
                Ok(APINodeContract {
                    contract_name: contract.name.clone(),
                    state_block_height: block_height,
                    state_commitment: contract.state,
                    program_id: contract.program_id,
                    verifier: contract.verifier,
                    timeout_window: match contract.timeout_window {
                        TimeoutWindow::NoTimeout => None,
                        TimeoutWindow::Timeout {
                            hard_timeout,
                            soft_timeout,
                        } => Some((hard_timeout.0, soft_timeout.0)),
                    },
                })
            })
        }

        fn get_unsettled_tx(
            &self,
            blob_tx_hash: TxHash,
        ) -> Pin<Box<dyn Future<Output = Result<UnsettledBlobTransaction>> + Send + '_>> {
            Box::pin(async move {
                self.unsettled_txs
                    .lock()
                    .unwrap()
                    .get(&blob_tx_hash)
                    .cloned()
                    .ok_or_else(|| anyhow::anyhow!("Unsettled transaction not found"))
            })
        }

        fn get_settled_height(
            &self,
            _contract_name: ContractName,
        ) -> Pin<Box<dyn Future<Output = Result<BlockHeight>> + Send + '_>> {
            Box::pin(async move { Ok(*self.settled_height.lock().unwrap()) })
        }
    }
}