lichen-client-sdk 0.1.5

Lichen Rust SDK - Build on Lichen with Rust
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
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
//! RPC client for Lichen

use crate::error::{Error, Result};
use crate::types::{Balance, Block, NetworkInfo};
use crate::{
    ContractInstruction, Hash, Instruction, Keypair, Pubkey, TransactionBuilder,
    CONTRACT_PROGRAM_ID, SYSTEM_PROGRAM_ID,
};
use reqwest;
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ReadonlyContractResult {
    pub success: bool,
    #[serde(rename = "returnData")]
    pub return_data: Option<String>,
    #[serde(rename = "returnCode")]
    pub return_code: Option<u32>,
    #[serde(default)]
    pub logs: Vec<String>,
    pub error: Option<String>,
    #[serde(rename = "computeUsed")]
    pub compute_used: Option<u64>,
}

/// Lichen RPC client
#[derive(Debug, Clone)]
pub struct Client {
    rpc_url: String,
    client: reqwest::Client,
    next_id: Arc<AtomicU64>,
}

impl Client {
    /// Create a new client with default settings
    pub fn new(rpc_url: impl Into<String>) -> Self {
        Self {
            rpc_url: rpc_url.into(),
            client: reqwest::Client::new(),
            next_id: Arc::new(AtomicU64::new(1)),
        }
    }

    /// Create a client using the LICHEN_RPC_URL env var, falling back to localhost:8899.
    pub fn from_env() -> Self {
        let url =
            std::env::var("LICHEN_RPC_URL").unwrap_or_else(|_| "http://localhost:8899".to_string());
        Self::new(url)
    }

    /// Create a client builder for custom configuration
    pub fn builder() -> ClientBuilder {
        ClientBuilder::default()
    }

    /// Make an RPC call
    pub(crate) async fn rpc_call(&self, method: &str, params: Value) -> Result<Value> {
        let id = self.next_id.fetch_add(1, Ordering::Relaxed);
        let request = json!({
            "jsonrpc": "2.0",
            "id": id,
            "method": method,
            "params": params
        });

        let response = self
            .client
            .post(&self.rpc_url)
            .json(&request)
            .send()
            .await?
            .json::<Value>()
            .await?;

        if let Some(error) = response.get("error") {
            return Err(Error::RpcError(error.to_string()));
        }

        response
            .get("result")
            .cloned()
            .ok_or(Error::RpcError("No result in response".to_string()))
    }

    /// Get current slot
    pub async fn get_slot(&self) -> Result<u64> {
        let result = self.rpc_call("getSlot", json!([])).await?;
        result
            .as_u64()
            .ok_or(Error::ParseError("Invalid slot format".to_string()))
    }

    /// Get account balance
    pub async fn get_balance(&self, pubkey: &Pubkey) -> Result<Balance> {
        let result = self
            .rpc_call("getBalance", json!([pubkey.to_base58()]))
            .await?;

        let spores = result["spores"]
            .as_u64()
            .ok_or(Error::ParseError("Invalid balance format".to_string()))?;

        Ok(Balance::from_spores(spores))
    }

    /// Get block by slot
    pub async fn get_block(&self, slot: u64) -> Result<Block> {
        let result = self.rpc_call("getBlock", json!([slot])).await?;
        serde_json::from_value(result).map_err(|e| Error::ParseError(e.to_string()))
    }

    /// Get latest block
    pub async fn get_latest_block(&self) -> Result<Block> {
        let result = self.rpc_call("getLatestBlock", json!([])).await?;
        serde_json::from_value(result).map_err(|e| Error::ParseError(e.to_string()))
    }

    /// Get network information
    pub async fn get_network_info(&self) -> Result<NetworkInfo> {
        let result = self.rpc_call("getNetworkInfo", json!([])).await?;
        serde_json::from_value(result).map_err(|e| Error::ParseError(e.to_string()))
    }

    /// Get validators
    pub async fn get_validators(&self) -> Result<Vec<Value>> {
        let result = self.rpc_call("getValidators", json!([])).await?;
        // Handle both array format and object with "validators" field
        if let Some(arr) = result.as_array() {
            Ok(arr.clone())
        } else if let Some(validators) = result.get("validators").and_then(|v| v.as_array()) {
            Ok(validators.clone())
        } else {
            Err(Error::ParseError("Invalid validators format".to_string()))
        }
    }

    /// Send raw transaction (base64-encoded bincode)
    pub async fn send_raw_transaction(&self, tx_base64: &str) -> Result<String> {
        let result = self.rpc_call("sendTransaction", json!([tx_base64])).await?;
        result
            .as_str()
            .map(|s| s.to_string())
            .ok_or(Error::ParseError("Invalid transaction hash".to_string()))
    }

    /// Send transaction (serializes with wire envelope and encodes automatically)
    pub async fn send_transaction(&self, tx: &crate::types::Transaction) -> Result<String> {
        let tx_bytes = tx.to_wire();
        let tx_base64 =
            base64::Engine::encode(&base64::engine::general_purpose::STANDARD, &tx_bytes);
        self.send_raw_transaction(&tx_base64).await
    }

    /// Get transaction by signature
    pub async fn get_transaction(&self, signature: &str) -> Result<Value> {
        self.rpc_call("getTransaction", json!([signature])).await
    }

    /// Get account info
    pub async fn get_account_info(&self, pubkey: &Pubkey) -> Result<Value> {
        self.rpc_call("getAccountInfo", json!([pubkey.to_base58()]))
            .await
    }

    /// Get transaction history for an account
    pub async fn get_transaction_history(
        &self,
        pubkey: &Pubkey,
        limit: Option<u64>,
    ) -> Result<Value> {
        let limit = limit.unwrap_or(10);
        self.rpc_call("getTransactionHistory", json!([pubkey.to_base58(), limit]))
            .await
    }

    /// Execute a read-only contract call without submitting a transaction.
    pub async fn call_readonly_contract(
        &self,
        contract: &Pubkey,
        function: &str,
        args: Vec<u8>,
        from: Option<&Pubkey>,
    ) -> Result<ReadonlyContractResult> {
        let args_b64 = base64::Engine::encode(&base64::engine::general_purpose::STANDARD, &args);
        let mut params = vec![
            json!(contract.to_base58()),
            json!(function),
            json!(args_b64),
        ];
        if let Some(from_pubkey) = from {
            params.push(json!(from_pubkey.to_base58()));
        }

        let result = self.rpc_call("callContract", Value::Array(params)).await?;
        serde_json::from_value(result).map_err(|err| Error::ParseError(err.to_string()))
    }

    /// Get recent blockhash (for transaction building)
    pub async fn get_recent_blockhash(&self) -> Result<String> {
        let result = self.rpc_call("getRecentBlockhash", json!([])).await?;
        // Handle both string format and object with "blockhash" field
        if let Some(hash_str) = result.as_str() {
            Ok(hash_str.to_string())
        } else if let Some(hash_str) = result.get("blockhash").and_then(|v| v.as_str()) {
            Ok(hash_str.to_string())
        } else {
            Err(Error::ParseError("Invalid blockhash format".to_string()))
        }
    }

    // ============================================================================
    // VALIDATOR OPERATIONS
    // ============================================================================

    /// Get detailed validator information
    pub async fn get_validator_info(&self, pubkey: &Pubkey) -> Result<Value> {
        self.rpc_call("getValidatorInfo", json!([pubkey.to_base58()]))
            .await
    }

    /// Get validator performance metrics
    pub async fn get_validator_performance(&self, pubkey: &Pubkey) -> Result<Value> {
        self.rpc_call("getValidatorPerformance", json!([pubkey.to_base58()]))
            .await
    }

    /// Get comprehensive chain status
    pub async fn get_chain_status(&self) -> Result<Value> {
        self.rpc_call("getChainStatus", json!([])).await
    }

    // ============================================================================
    // STAKING OPERATIONS
    // ============================================================================

    /// Create stake transaction
    pub async fn stake(&self, staker: &Keypair, validator: &Pubkey, amount: u64) -> Result<String> {
        let blockhash_str = self.get_recent_blockhash().await?;
        let blockhash = Hash::from_hex(&blockhash_str).map_err(|e| Error::ParseError(e))?;

        let mut data = vec![9u8];
        data.extend_from_slice(&amount.to_le_bytes());

        let instruction = Instruction {
            program_id: SYSTEM_PROGRAM_ID,
            accounts: vec![staker.pubkey(), *validator],
            data,
        };

        let tx = TransactionBuilder::new()
            .add_instruction(instruction)
            .recent_blockhash(blockhash)
            .build_and_sign(staker)?;

        self.send_transaction(&tx).await
    }

    /// Create unstake transaction
    pub async fn unstake(
        &self,
        staker: &Keypair,
        validator: &Pubkey,
        amount: u64,
    ) -> Result<String> {
        let blockhash_str = self.get_recent_blockhash().await?;
        let blockhash = Hash::from_hex(&blockhash_str).map_err(|e| Error::ParseError(e))?;

        let mut data = vec![10u8];
        data.extend_from_slice(&amount.to_le_bytes());

        let instruction = Instruction {
            program_id: SYSTEM_PROGRAM_ID,
            accounts: vec![staker.pubkey(), *validator],
            data,
        };

        let tx = TransactionBuilder::new()
            .add_instruction(instruction)
            .recent_blockhash(blockhash)
            .build_and_sign(staker)?;

        self.send_transaction(&tx).await
    }

    /// Get staking status for an account
    pub async fn get_staking_status(&self, pubkey: &Pubkey) -> Result<Value> {
        self.rpc_call("getStakingStatus", json!([pubkey.to_base58()]))
            .await
    }

    /// Get staking rewards for an account
    pub async fn get_staking_rewards(&self, pubkey: &Pubkey) -> Result<Value> {
        self.rpc_call("getStakingRewards", json!([pubkey.to_base58()]))
            .await
    }

    // ============================================================================
    // TRANSFER & CONTRACT OPERATIONS
    // ============================================================================

    /// Transfer native LICN (spores) from one account to another.
    pub async fn transfer(&self, from: &Keypair, to: &Pubkey, amount: u64) -> Result<String> {
        let blockhash_str = self.get_recent_blockhash().await?;
        let blockhash = Hash::from_hex(&blockhash_str).map_err(|e| Error::ParseError(e))?;

        let mut data = vec![0u8]; // Transfer instruction type
        data.extend_from_slice(&amount.to_le_bytes());

        let instruction = Instruction {
            program_id: SYSTEM_PROGRAM_ID,
            accounts: vec![from.pubkey(), *to],
            data,
        };

        let tx = TransactionBuilder::new()
            .add_instruction(instruction)
            .recent_blockhash(blockhash)
            .build_and_sign(from)?;

        self.send_transaction(&tx).await
    }

    /// Deploy a WASM smart contract.
    ///
    /// # Arguments
    /// * `deployer` - Deployer keypair (signer, pays deploy fee)
    /// * `code` - WASM bytecode (must start with \0asm magic, max 512 KB)
    /// * `init_data` - Optional initialization data passed to contract init
    pub async fn deploy_contract(
        &self,
        deployer: &Keypair,
        code: Vec<u8>,
        init_data: Vec<u8>,
    ) -> Result<String> {
        if code.len() < 4 || &code[..4] != b"\0asm" {
            return Err(Error::BuildError(
                "Invalid WASM bytecode: missing magic header (\\0asm)".into(),
            ));
        }
        if code.len() > 512 * 1024 {
            return Err(Error::BuildError(
                "Contract code exceeds 512 KB limit".into(),
            ));
        }

        let blockhash_str = self.get_recent_blockhash().await?;
        let blockhash = Hash::from_hex(&blockhash_str).map_err(|e| Error::ParseError(e))?;

        let contract_ix = ContractInstruction::Deploy { code, init_data };
        let data = serde_json::to_vec(&contract_ix)
            .map_err(|e| Error::SerializationError(e.to_string()))?;

        let instruction = Instruction {
            program_id: CONTRACT_PROGRAM_ID,
            accounts: vec![deployer.pubkey()],
            data,
        };

        let tx = TransactionBuilder::new()
            .add_instruction(instruction)
            .recent_blockhash(blockhash)
            .build_and_sign(deployer)?;

        self.send_transaction(&tx).await
    }

    /// Call a function on a deployed WASM smart contract.
    ///
    /// # Arguments
    /// * `caller` - Caller keypair (signer)
    /// * `contract` - Contract account public key
    /// * `function` - Name of the contract function to invoke
    /// * `args` - Serialized function arguments
    /// * `value` - Native LICN to send with the call in spores
    pub async fn call_contract(
        &self,
        caller: &Keypair,
        contract: &Pubkey,
        function: &str,
        args: Vec<u8>,
        value: u64,
    ) -> Result<String> {
        let blockhash_str = self.get_recent_blockhash().await?;
        let blockhash = Hash::from_hex(&blockhash_str).map_err(|e| Error::ParseError(e))?;

        let contract_ix = ContractInstruction::Call {
            function: function.to_string(),
            args,
            value,
        };
        let data = serde_json::to_vec(&contract_ix)
            .map_err(|e| Error::SerializationError(e.to_string()))?;

        let instruction = Instruction {
            program_id: CONTRACT_PROGRAM_ID,
            accounts: vec![caller.pubkey(), *contract],
            data,
        };

        let tx = TransactionBuilder::new()
            .add_instruction(instruction)
            .recent_blockhash(blockhash)
            .build_and_sign(caller)?;

        self.send_transaction(&tx).await
    }

    /// Upgrade a deployed WASM smart contract (owner only).
    pub async fn upgrade_contract(
        &self,
        owner: &Keypair,
        contract: &Pubkey,
        code: Vec<u8>,
    ) -> Result<String> {
        if code.len() < 4 || &code[..4] != b"\0asm" {
            return Err(Error::BuildError(
                "Invalid WASM bytecode: missing magic header (\\0asm)".into(),
            ));
        }
        if code.len() > 512 * 1024 {
            return Err(Error::BuildError(
                "Contract code exceeds 512 KB limit".into(),
            ));
        }

        let blockhash_str = self.get_recent_blockhash().await?;
        let blockhash = Hash::from_hex(&blockhash_str).map_err(|e| Error::ParseError(e))?;

        let contract_ix = ContractInstruction::Upgrade { code };
        let data = serde_json::to_vec(&contract_ix)
            .map_err(|e| Error::SerializationError(e.to_string()))?;

        let instruction = Instruction {
            program_id: CONTRACT_PROGRAM_ID,
            accounts: vec![owner.pubkey(), *contract],
            data,
        };

        let tx = TransactionBuilder::new()
            .add_instruction(instruction)
            .recent_blockhash(blockhash)
            .build_and_sign(owner)?;

        self.send_transaction(&tx).await
    }

    // ============================================================================
    // NETWORK OPERATIONS
    // ============================================================================

    /// Get connected peers
    pub async fn get_peers(&self) -> Result<Value> {
        self.rpc_call("getPeers", json!([])).await
    }

    /// Get network metrics
    pub async fn get_metrics(&self) -> Result<Value> {
        self.rpc_call("getMetrics", json!([])).await
    }

    /// Get total burned tokens
    pub async fn get_total_burned(&self) -> Result<Value> {
        self.rpc_call("getTotalBurned", json!([])).await
    }

    // ============================================================================
    // CONTRACT/PROGRAM OPERATIONS
    // ============================================================================

    /// Get contract information
    pub async fn get_contract_info(&self, contract_id: &Pubkey) -> Result<Value> {
        self.rpc_call("getContractInfo", json!([contract_id.to_base58()]))
            .await
    }

    /// Get contract execution logs
    pub async fn get_contract_logs(&self, contract_id: &Pubkey) -> Result<Value> {
        self.rpc_call("getContractLogs", json!([contract_id.to_base58()]))
            .await
    }

    /// Get a symbol-registry entry.
    pub async fn get_symbol_registry(&self, symbol: &str) -> Result<Value> {
        self.rpc_call("getSymbolRegistry", json!([symbol])).await
    }

    /// Get the complete LichenID profile for an address.
    pub async fn get_lichenid_profile(&self, pubkey: &Pubkey) -> Result<Value> {
        self.rpc_call("getLichenIdProfile", json!([pubkey.to_base58()]))
            .await
    }

    /// Get the LichenID reputation summary for an address.
    pub async fn get_lichenid_reputation(&self, pubkey: &Pubkey) -> Result<Value> {
        self.rpc_call("getLichenIdReputation", json!([pubkey.to_base58()]))
            .await
    }

    /// Get LichenID skills for an address.
    pub async fn get_lichenid_skills(&self, pubkey: &Pubkey) -> Result<Value> {
        self.rpc_call("getLichenIdSkills", json!([pubkey.to_base58()]))
            .await
    }

    /// Get LichenID vouches for an address.
    pub async fn get_lichenid_vouches(&self, pubkey: &Pubkey) -> Result<Value> {
        self.rpc_call("getLichenIdVouches", json!([pubkey.to_base58()]))
            .await
    }

    /// Resolve a .lichen name to its owner.
    pub async fn resolve_lichen_name(&self, name: &str) -> Result<Value> {
        self.rpc_call("resolveLichenName", json!([name])).await
    }

    /// Get premium-name auction state for a .lichen label.
    pub async fn get_name_auction(&self, name: &str) -> Result<Value> {
        self.rpc_call("getNameAuction", json!([name])).await
    }

    /// Get the LichenID agent directory.
    pub async fn get_lichenid_agent_directory(&self, options: Option<Value>) -> Result<Value> {
        match options {
            Some(options) => {
                self.rpc_call("getLichenIdAgentDirectory", json!([options]))
                    .await
            }
            None => self.rpc_call("getLichenIdAgentDirectory", json!([])).await,
        }
    }

    /// Get aggregated LichenID statistics.
    pub async fn get_lichenid_stats(&self) -> Result<Value> {
        self.rpc_call("getLichenIdStats", json!([])).await
    }

    /// Get aggregated SporePay streaming statistics.
    pub async fn get_sporepay_stats(&self) -> Result<Value> {
        self.rpc_call("getSporePayStats", json!([])).await
    }

    /// Get aggregated LichenSwap statistics.
    pub async fn get_lichenswap_stats(&self) -> Result<Value> {
        self.rpc_call("getLichenSwapStats", json!([])).await
    }

    /// Get aggregated ThallLend lending statistics.
    pub async fn get_thalllend_stats(&self) -> Result<Value> {
        self.rpc_call("getThallLendStats", json!([])).await
    }

    /// Get aggregated SporeVault yield-vault statistics.
    pub async fn get_sporevault_stats(&self) -> Result<Value> {
        self.rpc_call("getSporeVaultStats", json!([])).await
    }

    /// Get aggregated Neo GAS rewards vault statistics.
    pub async fn get_neo_gas_rewards_stats(&self) -> Result<Value> {
        self.rpc_call("getNeoGasRewardsStats", json!([])).await
    }

    /// Get per-wallet Neo GAS rewards vault accounting.
    pub async fn get_neo_gas_rewards_position(&self, address: &Pubkey) -> Result<Value> {
        self.rpc_call("getNeoGasRewardsPosition", json!([address.to_base58()]))
            .await
    }

    /// Get Neo reserve/liability proof-service verifier metadata.
    pub async fn get_neo_zk_proof_service_status(&self) -> Result<Value> {
        self.rpc_call("getNeoZkProofServiceStatus", json!([])).await
    }

    /// Verify a CLI-produced Neo reserve/liability proof envelope.
    pub async fn verify_neo_reserve_liability_proof(&self, proof_envelope: Value) -> Result<Value> {
        self.rpc_call("verifyNeoReserveLiabilityProof", json!([proof_envelope]))
            .await
    }

    /// Get aggregated BountyBoard marketplace statistics.
    pub async fn get_bountyboard_stats(&self) -> Result<Value> {
        self.rpc_call("getBountyBoardStats", json!([])).await
    }

    // ============================================================================
    // PROGRAM OPERATIONS (DRAFT)
    // ============================================================================

    pub async fn get_program(&self, program_id: &Pubkey) -> Result<Value> {
        self.rpc_call("getProgram", json!([program_id.to_base58()]))
            .await
    }

    pub async fn get_program_stats(&self, program_id: &Pubkey) -> Result<Value> {
        self.rpc_call("getProgramStats", json!([program_id.to_base58()]))
            .await
    }

    pub async fn get_programs(&self) -> Result<Value> {
        self.rpc_call("getPrograms", json!([])).await
    }

    pub async fn get_program_calls(&self, program_id: &Pubkey) -> Result<Value> {
        self.rpc_call("getProgramCalls", json!([program_id.to_base58()]))
            .await
    }

    pub async fn get_program_storage(&self, program_id: &Pubkey) -> Result<Value> {
        self.rpc_call("getProgramStorage", json!([program_id.to_base58()]))
            .await
    }

    // ============================================================================
    // NFT OPERATIONS (DRAFT)
    // ============================================================================

    pub async fn get_collection(&self, collection_id: &Pubkey) -> Result<Value> {
        self.rpc_call("getCollection", json!([collection_id.to_base58()]))
            .await
    }

    pub async fn get_nft(&self, collection_id: &Pubkey, token_id: u64) -> Result<Value> {
        self.rpc_call("getNFT", json!([collection_id.to_base58(), token_id]))
            .await
    }

    pub async fn get_nfts_by_owner(&self, owner: &Pubkey) -> Result<Value> {
        self.rpc_call("getNFTsByOwner", json!([owner.to_base58()]))
            .await
    }

    pub async fn get_nfts_by_collection(&self, collection_id: &Pubkey) -> Result<Value> {
        self.rpc_call("getNFTsByCollection", json!([collection_id.to_base58()]))
            .await
    }

    pub async fn get_nft_activity(&self, collection_id: &Pubkey, token_id: u64) -> Result<Value> {
        self.rpc_call(
            "getNFTActivity",
            json!([collection_id.to_base58(), token_id]),
        )
        .await
    }

    /// Get all deployed contracts
    pub async fn get_all_contracts(&self) -> Result<Value> {
        self.rpc_call("getAllContracts", json!([])).await
    }

    /// Health check
    pub async fn health(&self) -> Result<bool> {
        let result = self.rpc_call("health", json!([])).await?;
        Ok(result.get("status").and_then(|v| v.as_str()) == Some("ok"))
    }
}

/// Builder for Client with custom configuration
#[derive(Default)]
pub struct ClientBuilder {
    rpc_url: Option<String>,
    timeout: Option<std::time::Duration>,
}

impl ClientBuilder {
    /// Set RPC URL
    pub fn rpc_url(mut self, url: impl Into<String>) -> Self {
        self.rpc_url = Some(url.into());
        self
    }

    /// Set request timeout
    pub fn timeout(mut self, timeout: std::time::Duration) -> Self {
        self.timeout = Some(timeout);
        self
    }

    /// Build the client
    pub fn build(self) -> Result<Client> {
        let rpc_url = self
            .rpc_url
            .ok_or(Error::ConfigError("RPC URL not set".to_string()))?;

        let mut client_builder = reqwest::Client::builder();

        if let Some(timeout) = self.timeout {
            client_builder = client_builder.timeout(timeout);
        }

        Ok(Client {
            rpc_url,
            client: client_builder.build()?,
            next_id: Arc::new(AtomicU64::new(1)),
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::{Mutex, OnceLock};

    fn env_lock() -> &'static Mutex<()> {
        static LOCK: OnceLock<Mutex<()>> = OnceLock::new();
        LOCK.get_or_init(|| Mutex::new(()))
    }

    // ── Client::new ─────────────────────────────────────────────────

    #[test]
    fn test_client_new() {
        let client = Client::new("http://localhost:8899");
        assert_eq!(client.rpc_url, "http://localhost:8899");
    }

    #[test]
    fn test_client_new_custom_url() {
        let client = Client::new("https://rpc.lichen.network:443");
        assert_eq!(client.rpc_url, "https://rpc.lichen.network:443");
    }

    #[test]
    fn test_client_new_id_starts_at_1() {
        let client = Client::new("http://localhost:8899");
        assert_eq!(client.next_id.load(Ordering::Relaxed), 1);
    }

    // ── Client::from_env ────────────────────────────────────────────

    #[test]
    fn test_client_from_env_defaults_to_localhost() {
        let _guard = env_lock().lock().unwrap();
        // Clear the env var to ensure fallback
        std::env::remove_var("LICHEN_RPC_URL");
        let client = Client::from_env();
        assert_eq!(client.rpc_url, "http://localhost:8899");
    }

    #[test]
    fn test_client_from_env_uses_var() {
        let _guard = env_lock().lock().unwrap();
        std::env::set_var("LICHEN_RPC_URL", "http://custom:9999");
        let client = Client::from_env();
        assert_eq!(client.rpc_url, "http://custom:9999");
        std::env::remove_var("LICHEN_RPC_URL");
    }

    // ── ClientBuilder ───────────────────────────────────────────────

    #[test]
    fn test_client_builder() {
        let client = Client::builder()
            .rpc_url("http://localhost:8899")
            .timeout(std::time::Duration::from_secs(30))
            .build()
            .expect("should build client");
        assert_eq!(client.rpc_url, "http://localhost:8899");
    }

    #[test]
    fn test_client_builder_no_url_fails() {
        let result = Client::builder().build();
        assert!(result.is_err(), "should fail without URL");
    }

    #[test]
    fn test_client_builder_no_timeout() {
        let client = Client::builder()
            .rpc_url("http://localhost:8899")
            .build()
            .expect("should build without timeout");
        assert_eq!(client.rpc_url, "http://localhost:8899");
    }

    #[test]
    fn test_client_builder_default() {
        let builder = ClientBuilder::default();
        assert!(builder.rpc_url.is_none());
        assert!(builder.timeout.is_none());
    }

    // ── Request ID counter ──────────────────────────────────────────

    #[test]
    fn test_client_id_increments() {
        let client = Client::new("http://localhost:8899");
        let v1 = client.next_id.fetch_add(1, Ordering::Relaxed);
        let v2 = client.next_id.fetch_add(1, Ordering::Relaxed);
        assert_eq!(v1, 1);
        assert_eq!(v2, 2);
    }

    #[test]
    fn test_client_clone_shares_counter() {
        let client = Client::new("http://localhost:8899");
        client.next_id.fetch_add(1, Ordering::Relaxed);
        let clone = client.clone();
        let v = clone.next_id.fetch_add(1, Ordering::Relaxed);
        assert_eq!(v, 2); // Shared via Arc
    }

    #[test]
    fn test_client_clone_shares_url() {
        let client = Client::new("http://my-rpc:8899");
        let clone = client.clone();
        assert_eq!(clone.rpc_url, "http://my-rpc:8899");
    }
}