rialo-cdk 0.2.0-alpha.0

Rialo CDK - A comprehensive toolkit for building with the Rialo blockchain
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
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
// Copyright (c) Subzero Labs, Inc.
// SPDX-License-Identifier: Apache-2.0

use rialo_api_types::messages::submit_epoch_change::{
    SubmitEpochChangeRequest, SubmitEpochChangeResponse,
};

use crate::rpc::types::{
    GetSecretSharingPubkeyResponse, GetTriggeredTransactionsResponse, GetWorkflowLineageResponse,
    WorkflowLineage,
};

/// Business-level mock RPC client for testing.
/// Returns business objects directly rather than mocking HTTP responses.
pub struct MockRpcClient {
    /// Pre-configured business object responses
    pub account_info: Option<crate::rpc::types::AccountInfo>,
    pub balance: u64,
    pub signature: crate::rpc::types::Signature,
    pub block_height: u64,
    pub slot: u64,
    pub transaction: Option<crate::rpc::types::Transaction>,
    pub transaction_count: u64,
    pub rent_exemption: u64,
    pub signature_statuses: Vec<Option<crate::rpc::types::SignatureStatus>>,
    pub subscriptions: Vec<rialo_shared_types::Subscription>,
    pub triggered_transactions: crate::rpc::types::GetTriggeredTransactionsResponse,
    pub workflow_lineage: crate::rpc::types::GetWorkflowLineageResponse,
    /// Optional error message to return instead of success responses
    pub error_message: Option<String>,
}

/// Mock signature constant used in tests.
/// This is a valid base58-encoded signature format.
pub const MOCK_SIGNATURE: &str =
    "4rWVz1CniwxGQJTZkxLfKc9qCCPGAL1HKLHJWkAdbfdiJeXRJkpvHxHjvEZMtWrJdXKFKBSRVdGLKFMK2jsQCXWx";

/// Mock blockhash constant used in tests.
/// This is a valid base58-encoded hash format.
pub const MOCK_BLOCKHASH: &str = "EkSnNWid2cvwEVnVx9aBqawnmiCNiDgp3gUdkDPTKN1N";

/// Mock slot number used in tests.
pub const MOCK_SLOT: u64 = 123456789;

/// Mock transaction fee used in tests (in kelvin).
pub const MOCK_FEE: u64 = 5000;

/// Error message used in tests.
pub const ERROR_MESSAGE: &str = "Invalid signature";

impl Default for MockRpcClient {
    fn default() -> Self {
        use std::str::FromStr;

        use crate::rpc::types::*;

        Self {
            account_info: Some(AccountInfo {
                kelvin: 100,
                owner: rialo_s_sdk::system_program::id().to_string(),
                data: vec![],
                executable: false,
                rent_epoch: 0,
                space: 0,
            }),
            balance: 100,
            signature: Signature::from_str(MOCK_SIGNATURE).unwrap(),
            block_height: MOCK_SLOT, // Use same value as slot for consistency
            slot: MOCK_SLOT,
            transaction: Some(Transaction {
                signatures: vec![Signature::from_str(MOCK_SIGNATURE).unwrap().to_string()],
                message: TransactionMessage {
                    header: MessageHeader {
                        num_required_signatures: 1,
                        num_readonly_signed_accounts: 0,
                        num_readonly_unsigned_accounts: 1,
                    },
                    account_keys: vec![
                        Pubkey::new_unique().to_string(),
                        rialo_s_sdk::system_program::id().to_string(),
                    ],
                    instructions: vec![],
                },
                valid_from: 0, // Default for mock
            }),
            transaction_count: 1000,
            rent_exemption: 2039280,
            signature_statuses: vec![Some(SignatureStatus {
                slot: MOCK_SLOT,
                err: None,
                executed: true,
            })],
            subscriptions: vec![],
            triggered_transactions: GetTriggeredTransactionsResponse {
                transactions: vec![],
            },
            workflow_lineage: GetWorkflowLineageResponse {
                lineage: WorkflowLineage {
                    workflow_nodes: vec![],
                },
                leaves: vec![],
                truncated: false,
                truncation_reason: crate::rpc::types::TruncationReason::None,
                continuation_hints: vec![],
            },
            error_message: None,
        }
    }
}

impl MockRpcClient {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn with_error(mut self, error_message: String) -> Self {
        self.error_message = Some(error_message);
        self
    }

    pub fn with_account_info(mut self, account_info: crate::rpc::types::AccountInfo) -> Self {
        self.account_info = Some(account_info);
        self
    }

    pub fn with_no_account(mut self) -> Self {
        self.account_info = None;
        self
    }

    pub fn with_balance(mut self, balance: u64) -> Self {
        self.balance = balance;
        self
    }

    pub fn with_signature(mut self, signature: crate::rpc::types::Signature) -> Self {
        self.signature = signature;
        self
    }

    pub fn with_transaction(mut self, transaction: crate::rpc::types::Transaction) -> Self {
        self.transaction = Some(transaction);
        self
    }

    pub fn with_transaction_count(mut self, count: u64) -> Self {
        self.transaction_count = count;
        self
    }

    pub fn with_rent_exemption(mut self, rent_exemption: u64) -> Self {
        self.rent_exemption = rent_exemption;
        self
    }

    pub fn with_slot(mut self, slot: u64) -> Self {
        self.slot = slot;
        self
    }

    /// Sets the mock block height value that will be returned by get_block_height calls.
    pub fn with_block_height(mut self, block_height: u64) -> Self {
        self.block_height = block_height;
        self
    }

    pub fn with_subscriptions(
        mut self,
        subscriptions: Vec<rialo_shared_types::Subscription>,
    ) -> Self {
        self.subscriptions = subscriptions;
        self
    }

    pub fn with_triggered_transactions(
        mut self,
        triggered_transactions: crate::rpc::types::GetTriggeredTransactionsResponse,
    ) -> Self {
        self.triggered_transactions = triggered_transactions;
        self
    }

    pub fn with_signature_statuses(
        mut self,
        signature_statuses: Vec<Option<crate::rpc::types::SignatureStatus>>,
    ) -> Self {
        self.signature_statuses = signature_statuses;
        self
    }
}

/// Implement RpcClient trait for MockRpcClient with business-level responses
#[cfg_attr(not(target_arch = "wasm32"), async_trait::async_trait)]
#[cfg_attr(target_arch = "wasm32", async_trait::async_trait(?Send))]
impl crate::rpc::traits::RpcClient for MockRpcClient {
    async fn call_with_json(
        &self,
        _method: &str,
        _params: serde_json::Value,
    ) -> crate::error::Result<serde_json::Value> {
        if let Some(error_msg) = &self.error_message {
            return Err(crate::error::RialoError::Rpc(
                crate::error::RpcErrorDetails::from_message(error_msg.clone()),
            ));
        }
        // Return a generic success response - tests should use specific methods instead
        Ok(serde_json::json!({"success": true}))
    }

    async fn get_balance(&self, _pubkey: &crate::rpc::types::Pubkey) -> crate::error::Result<u64> {
        if let Some(error_msg) = &self.error_message {
            return Err(crate::error::RialoError::Rpc(
                crate::error::RpcErrorDetails::from_message(error_msg.clone()),
            ));
        }
        Ok(self.balance)
    }

    async fn send_transaction(
        &self,
        _transaction: &[u8],
        _options: Option<crate::rpc::types::SendTransactionOptions>,
    ) -> crate::error::Result<crate::rpc::types::Signature> {
        if let Some(error_msg) = &self.error_message {
            return Err(crate::error::RialoError::Rpc(
                crate::error::RpcErrorDetails::from_message(error_msg.clone()),
            ));
        }
        Ok(self.signature)
    }

    async fn get_account_info(
        &self,
        _pubkey: &crate::rpc::types::Pubkey,
    ) -> crate::error::Result<crate::rpc::types::AccountInfo> {
        if let Some(error_msg) = &self.error_message {
            return Err(crate::error::RialoError::Rpc(
                crate::error::RpcErrorDetails::from_message(error_msg.clone()),
            ));
        }
        match &self.account_info {
            Some(info) => Ok(info.clone()),
            None => Err(crate::error::RialoError::Rpc(
                crate::error::RpcErrorDetails::from_message("Account not found".to_string()),
            )),
        }
    }

    /// Mock implementation of get_block_height for CLI testing.
    /// Returns the configured mock block height value or an error if error_message is set.
    async fn get_block_height(&self) -> crate::error::Result<u64> {
        if let Some(error_msg) = &self.error_message {
            return Err(crate::error::RialoError::Rpc(
                crate::error::RpcErrorDetails::from_message(error_msg.clone()),
            ));
        }
        Ok(self.block_height)
    }

    async fn get_block_height_with_config(
        &self,
        _min_context_slot: Option<u64>,
    ) -> crate::error::Result<u64> {
        // For CLI mock, just delegate to the basic method
        self.get_block_height().await
    }

    async fn get_transaction(
        &self,
        _signature: &crate::rpc::types::Signature,
    ) -> crate::error::Result<crate::rpc::types::TransactionResponse> {
        if let Some(error_msg) = &self.error_message {
            return Err(crate::error::RialoError::Rpc(
                crate::error::RpcErrorDetails::from_message(error_msg.clone()),
            ));
        }
        match &self.transaction {
            Some(tx) => Ok(crate::rpc::types::TransactionResponse {
                block_height: self.block_height,
                block_hash: MOCK_BLOCKHASH.to_string(),
                meta: crate::rpc::types::TransactionStatusMetadata {
                    log_messages: Some(vec![]),
                    err: None,
                    fee: MOCK_FEE,
                },
                transaction: crate::rpc::types::Transaction {
                    signatures: tx.signatures.clone(),
                    message: crate::rpc::types::TransactionMessage {
                        header: crate::rpc::types::MessageHeader {
                            num_required_signatures: tx.message.header.num_required_signatures,
                            num_readonly_signed_accounts: tx
                                .message
                                .header
                                .num_readonly_signed_accounts,
                            num_readonly_unsigned_accounts: tx
                                .message
                                .header
                                .num_readonly_unsigned_accounts,
                        },
                        account_keys: tx.message.account_keys.clone(),
                        instructions: vec![], // Simplify for tests
                    },
                    valid_from: 0, // Default for mock
                },
                block_time: None,
            }),
            None => Err(crate::error::RialoError::Rpc(
                crate::error::RpcErrorDetails::from_message("Transaction not found".to_string()),
            )),
        }
    }

    async fn get_transaction_count(&self) -> crate::error::Result<u64> {
        if let Some(error_msg) = &self.error_message {
            return Err(crate::error::RialoError::Rpc(
                crate::error::RpcErrorDetails::from_message(error_msg.clone()),
            ));
        }
        Ok(self.transaction_count)
    }

    async fn get_minimum_balance_for_rent_exemption(
        &self,
        _size: u64,
    ) -> crate::error::Result<u64> {
        if let Some(error_msg) = &self.error_message {
            return Err(crate::error::RialoError::Rpc(
                crate::error::RpcErrorDetails::from_message(error_msg.clone()),
            ));
        }
        Ok(self.rent_exemption)
    }

    async fn get_signature_statuses(
        &self,
        _signatures: &[crate::rpc::types::Signature],
    ) -> crate::error::Result<Vec<crate::rpc::types::SignatureStatus>> {
        if let Some(error_msg) = &self.error_message {
            return Err(crate::error::RialoError::Rpc(
                crate::error::RpcErrorDetails::from_message(error_msg.clone()),
            ));
        }
        let result: Vec<crate::rpc::types::SignatureStatus> = self
            .signature_statuses
            .iter()
            .filter_map(|opt_status| {
                opt_status
                    .as_ref()
                    .map(|status| crate::rpc::types::SignatureStatus {
                        slot: status.slot,
                        err: status.err.clone(),
                        executed: status.executed,
                    })
            })
            .collect();
        Ok(result)
    }

    async fn get_subscription(
        &self,
        _subscriber: &crate::rpc::types::Pubkey,
        _nonce: &str,
    ) -> crate::error::Result<crate::rpc::types::GetSubscriptionResponse> {
        if let Some(error_msg) = &self.error_message {
            return Err(crate::error::RialoError::Rpc(
                crate::error::RpcErrorDetails::from_message(error_msg.clone()),
            ));
        }
        // Return the first subscription from the mock, or error if none
        let subscription = self.subscriptions.first().cloned().ok_or_else(|| {
            crate::error::RialoError::Rpc(crate::error::RpcErrorDetails::from_message(
                "Subscription not found".to_string(),
            ))
        })?;
        Ok(crate::rpc::types::GetSubscriptionResponse {
            context: crate::rpc::types::RpcResponseContext {
                api_version: Some("1.0".to_string()),
                slot: MOCK_SLOT,
            },
            subscription,
        })
    }

    async fn get_triggered_transactions(
        &self,
        _subscription_account: &crate::rpc::types::Pubkey,
        _limit: Option<u32>,
    ) -> crate::error::Result<crate::rpc::types::GetTriggeredTransactionsResponse> {
        if let Some(error_msg) = &self.error_message {
            return Err(crate::error::RialoError::Rpc(
                crate::error::RpcErrorDetails::from_message(error_msg.clone()),
            ));
        }
        // Create new GetTriggeredTransactionsResponse instance
        let response = GetTriggeredTransactionsResponse {
            transactions: self
                .triggered_transactions
                .transactions
                .iter()
                .map(|tx| crate::rpc::types::TriggeredTransaction {
                    signature: tx.signature.clone(),
                    block_number: tx.block_number,
                })
                .collect(),
        };
        Ok(response)
    }

    async fn get_workflow_lineage(
        &self,
        _request: &crate::rpc::types::GetWorkflowLineageRequest,
    ) -> crate::error::Result<crate::rpc::types::GetWorkflowLineageResponse> {
        if let Some(error_msg) = &self.error_message {
            return Err(crate::error::RialoError::Rpc(
                crate::error::RpcErrorDetails::from_message(error_msg.clone()),
            ));
        }
        Ok(GetWorkflowLineageResponse {
            lineage: WorkflowLineage {
                workflow_nodes: vec![],
            },
            leaves: vec![],
            truncated: false,
            truncation_reason: crate::rpc::types::TruncationReason::None,
            continuation_hints: vec![],
        })
    }

    async fn request_airdrop(
        &self,
        _pubkey: &crate::rpc::types::Pubkey,
        _amount: u64,
    ) -> crate::error::Result<crate::rpc::types::Signature> {
        if let Some(error_msg) = &self.error_message {
            return Err(crate::error::RialoError::Rpc(
                crate::error::RpcErrorDetails::from_message(error_msg.clone()),
            ));
        }
        Ok(self.signature)
    }

    async fn get_epoch_info(&self) -> crate::error::Result<crate::rpc::types::EpochInfoResponse> {
        if let Some(error_msg) = &self.error_message {
            return Err(crate::error::RialoError::Rpc(
                crate::error::RpcErrorDetails::from_message(error_msg.clone()),
            ));
        }
        Ok(crate::rpc::types::EpochInfoResponse {
            absolute_slot: 166598,
            block_height: 166500,
            epoch: 27,
            slot_index: 2790,
            slots_in_epoch: 8192,
            transaction_count: Some(22),
        })
    }

    async fn get_fee_for_message(
        &self,
        _message: &str,
    ) -> crate::error::Result<crate::rpc::types::GetFeeForMessageResponse> {
        if let Some(error_msg) = &self.error_message {
            return Err(crate::error::RialoError::Rpc(
                crate::error::RpcErrorDetails::from_message(error_msg.clone()),
            ));
        }
        Ok(crate::rpc::types::GetFeeForMessageResponse {
            context: crate::rpc::types::RpcResponseContext {
                api_version: Some("1.0".to_string()),
                slot: MOCK_SLOT,
            },
            value: Some(5000),
        })
    }

    async fn get_multiple_accounts(
        &self,
        _pubkeys: &[crate::rpc::types::Pubkey],
    ) -> crate::error::Result<crate::rpc::types::MultipleAccountsResponse> {
        if let Some(error_msg) = &self.error_message {
            return Err(crate::error::RialoError::Rpc(
                crate::error::RpcErrorDetails::from_message(error_msg.clone()),
            ));
        }
        Ok(crate::rpc::types::MultipleAccountsResponse {
            context: crate::rpc::types::RpcResponseContext {
                api_version: Some("1.0".to_string()),
                slot: MOCK_SLOT,
            },
            value: vec![],
        })
    }

    async fn get_signatures_for_address(
        &self,
        _address: &crate::rpc::types::Pubkey,
        _config: Option<crate::rpc::types::GetSignaturesForAddressConfig>,
    ) -> crate::error::Result<crate::rpc::types::GetSignaturesForAddressResponse> {
        if let Some(error_msg) = &self.error_message {
            return Err(crate::error::RialoError::Rpc(
                crate::error::RpcErrorDetails::from_message(error_msg.clone()),
            ));
        }
        Ok(crate::rpc::types::GetSignaturesForAddressResponse {
            context: crate::rpc::types::RpcResponseContext {
                api_version: Some("1.0".to_string()),
                slot: MOCK_SLOT,
            },
            value: vec![],
        })
    }

    async fn is_blockhash_valid(
        &self,
        _blockhash: &crate::rpc::types::Hash,
    ) -> crate::error::Result<crate::rpc::types::IsBlockhashValidResponse> {
        if let Some(error_msg) = &self.error_message {
            return Err(crate::error::RialoError::Rpc(
                crate::error::RpcErrorDetails::from_message(error_msg.clone()),
            ));
        }
        Ok(crate::rpc::types::IsBlockhashValidResponse {
            context: crate::rpc::types::RpcResponseContext {
                api_version: Some("1.0".to_string()),
                slot: MOCK_SLOT,
            },
            value: true,
        })
    }

    async fn get_health(&self) -> crate::error::Result<crate::rpc::types::GetHealthResponse> {
        if let Some(error_msg) = &self.error_message {
            return Err(crate::error::RialoError::Rpc(
                crate::error::RpcErrorDetails::from_message(error_msg.clone()),
            ));
        }
        // Create a simple mock health response
        Ok(
            serde_json::from_str::<crate::rpc::types::GetHealthResponse>(r#"{\"status\":\"ok\"}"#)
                .unwrap(),
        )
    }

    async fn get_validator_health(
        &self,
    ) -> crate::error::Result<crate::rpc::types::GetValidatorHealthResponse> {
        if let Some(error_msg) = &self.error_message {
            return Err(crate::error::RialoError::Rpc(
                crate::error::RpcErrorDetails::from_message(error_msg.clone()),
            ));
        }
        // Create a simple mock validator health response
        Ok(
            serde_json::from_str::<crate::rpc::types::GetValidatorHealthResponse>(
                r#"{\"status\":\"ok\"}"#,
            )
            .unwrap(),
        )
    }

    async fn get_connected_full_nodes(
        &self,
    ) -> crate::error::Result<crate::rpc::types::GetConnectedFullNodesResponse> {
        if let Some(error_msg) = &self.error_message {
            return Err(crate::error::RialoError::Rpc(
                crate::error::RpcErrorDetails::from_message(error_msg.clone()),
            ));
        }
        Ok(crate::rpc::types::GetConnectedFullNodesResponse::new(
            vec![],
        ))
    }

    async fn get_transactions(
        &self,
        _config: Option<crate::rpc::types::GetTransactionsConfig>,
    ) -> crate::error::Result<crate::rpc::types::GetTransactionsResponse> {
        if let Some(error_msg) = &self.error_message {
            return Err(crate::error::RialoError::Rpc(
                crate::error::RpcErrorDetails::from_message(error_msg.clone()),
            ));
        }
        Ok(crate::rpc::types::GetTransactionsResponse::new(vec![], 0))
    }
    async fn get_secret_sharing_pubkey(
        &self,
    ) -> crate::Result<crate::rpc::types::GetSecretSharingPubkeyResponse> {
        if let Some(error_msg) = &self.error_message {
            return Err(crate::error::RialoError::Rpc(
                crate::error::RpcErrorDetails::from_message(error_msg.clone()),
            ));
        }
        Ok(GetSecretSharingPubkeyResponse::new(&[1u8; 32]))
    }

    async fn send_admin_transaction(
        &self,
        _params: SubmitEpochChangeRequest,
    ) -> crate::Result<SubmitEpochChangeResponse> {
        if let Some(error_msg) = &self.error_message {
            return Err(crate::error::RialoError::Rpc(
                crate::error::RpcErrorDetails::from_message(error_msg.clone()),
            ));
        }
        Ok(SubmitEpochChangeResponse { success: true })
    }

    async fn get_accounts_by_owner(
        &self,
        _owner: &crate::rpc::types::Pubkey,
    ) -> crate::Result<rialo_api_types::messages::get_accounts_by_owner::GetAccountsByOwnerResponse>
    {
        use rialo_api_types::messages::{
            get_accounts_by_owner::GetAccountsByOwnerResponse,
            rpc_response_context::RpcResponseContext,
        };

        if let Some(error_msg) = &self.error_message {
            return Err(crate::error::RialoError::Rpc(
                crate::error::RpcErrorDetails::from_message(error_msg.clone()),
            ));
        }

        // Return empty list by default
        Ok(GetAccountsByOwnerResponse {
            context: RpcResponseContext::new(self.slot),
            value: vec![],
            pagination: None,
        })
    }
}