outlayer-cli 0.1.1

CLI for deploying, running, and managing OutLayer agents
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use serde_json::Value;

use crate::config::NetworkConfig;

pub struct ApiClient {
    client: reqwest::Client,
    base_url: String,
}

#[derive(Debug, Serialize)]
pub struct HttpsCallRequest {
    pub input: Value,
    #[serde(rename = "async")]
    pub is_async: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub version_key: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub secrets_ref: Option<SecretsRef>,
}

#[derive(Debug, Clone, Serialize)]
pub struct SecretsRef {
    pub profile: String,
    pub account_id: String,
}

#[derive(Debug, Deserialize)]
pub struct HttpsCallResponse {
    pub call_id: String,
    pub status: String,
    pub output: Option<Value>,
    pub error: Option<String>,
    pub compute_cost: Option<String>,
    #[allow(dead_code)]
    pub instructions: Option<u64>,
    pub time_ms: Option<u64>,
    pub poll_url: Option<String>,
    #[allow(dead_code)]
    pub attestation_url: Option<String>,
}

#[derive(Debug, Serialize)]
pub struct GetPubkeyRequest {
    pub accessor: Value,
    pub owner: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub profile: Option<String>,
    pub secrets_json: String,
}

impl ApiClient {
    pub fn new(network: &NetworkConfig) -> Self {
        Self {
            client: reqwest::Client::new(),
            base_url: network.api_base_url.clone(),
        }
    }

    /// POST /call/{owner}/{project} — execute agent
    pub async fn call_project(
        &self,
        owner: &str,
        project: &str,
        payment_key: &str,
        body: &HttpsCallRequest,
        compute_limit: Option<u64>,
        deposit: Option<&str>,
    ) -> Result<HttpsCallResponse> {
        let url = format!("{}/call/{}/{}", self.base_url, owner, project);

        let mut req = self
            .client
            .post(&url)
            .header("X-Payment-Key", payment_key)
            .json(body);

        if let Some(limit) = compute_limit {
            req = req.header("X-Compute-Limit", limit.to_string());
        }
        if let Some(deposit) = deposit {
            req = req.header("X-Attached-Deposit", deposit);
        }

        let response = req.send().await.context("Failed to call project")?;

        if !response.status().is_success() {
            let status = response.status();
            let text = response.text().await.unwrap_or_default();
            anyhow::bail!("API error ({status}): {text}");
        }

        response
            .json()
            .await
            .context("Failed to parse call response")
    }

    /// GET /calls/{call_id} — poll async call status
    pub async fn get_call_result(
        &self,
        call_id: &str,
        payment_key: &str,
    ) -> Result<HttpsCallResponse> {
        let url = format!("{}/calls/{}", self.base_url, call_id);

        let response = self
            .client
            .get(&url)
            .header("X-Payment-Key", payment_key)
            .send()
            .await
            .context("Failed to poll call status")?;

        if !response.status().is_success() {
            let status = response.status();
            let text = response.text().await.unwrap_or_default();
            anyhow::bail!("API error ({status}): {text}");
        }

        response.json().await.context("Failed to parse call result")
    }

    /// GET /public/payment-keys/{owner}/{nonce}/balance
    pub async fn get_payment_key_balance(
        &self,
        owner: &str,
        nonce: u32,
    ) -> Result<PaymentKeyBalanceResponse> {
        let url = format!(
            "{}/public/payment-keys/{}/{}/balance",
            self.base_url, owner, nonce
        );

        let response = self.client.get(&url).send().await?;

        if !response.status().is_success() {
            let status = response.status();
            let text = response.text().await.unwrap_or_default();
            anyhow::bail!("Failed to get balance ({status}): {text}");
        }

        response
            .json()
            .await
            .context("Failed to parse balance response")
    }

    /// GET /public/payment-keys/{owner}/{nonce}/usage
    pub async fn get_payment_key_usage(
        &self,
        owner: &str,
        nonce: u32,
        limit: i64,
        offset: i64,
    ) -> Result<PaymentKeyUsageResponse> {
        let url = format!(
            "{}/public/payment-keys/{}/{}/usage?limit={}&offset={}",
            self.base_url, owner, nonce, limit, offset
        );

        let response = self.client.get(&url).send().await?;

        if !response.status().is_success() {
            let status = response.status();
            let text = response.text().await.unwrap_or_default();
            anyhow::bail!("Failed to get usage ({status}): {text}");
        }

        response
            .json()
            .await
            .context("Failed to parse usage response")
    }

    /// GET /public/project-earnings/{project_owner}
    pub async fn get_project_owner_earnings(
        &self,
        owner: &str,
    ) -> Result<ProjectOwnerEarningsResponse> {
        let url = format!("{}/public/project-earnings/{}", self.base_url, owner);

        let response = self.client.get(&url).send().await?;

        if !response.status().is_success() {
            let status = response.status();
            let text = response.text().await.unwrap_or_default();
            anyhow::bail!("Failed to get earnings ({status}): {text}");
        }

        response
            .json()
            .await
            .context("Failed to parse earnings response")
    }

    /// GET /public/project-earnings/{project_owner}/history
    pub async fn get_earnings_history(
        &self,
        owner: &str,
        source: Option<&str>,
        limit: i64,
        offset: i64,
    ) -> Result<EarningsHistoryResponse> {
        let mut url = format!(
            "{}/public/project-earnings/{}/history?limit={}&offset={}",
            self.base_url, owner, limit, offset
        );
        if let Some(source) = source {
            url.push_str(&format!("&source={}", source));
        }

        let response = self.client.get(&url).send().await?;

        if !response.status().is_success() {
            let status = response.status();
            let text = response.text().await.unwrap_or_default();
            anyhow::bail!("Failed to get earnings history ({status}): {text}");
        }

        response
            .json()
            .await
            .context("Failed to parse earnings history")
    }

    /// POST /secrets/add_generated_secret — generate PROTECTED_* in TEE
    pub async fn add_generated_secret(
        &self,
        req: &Value,
    ) -> Result<AddGeneratedSecretResponse> {
        let url = format!("{}/secrets/add_generated_secret", self.base_url);

        let response = self
            .client
            .post(&url)
            .json(req)
            .send()
            .await
            .context("Failed to call add_generated_secret")?;

        if !response.status().is_success() {
            let status = response.status();
            let text = response.text().await.unwrap_or_default();
            anyhow::bail!("Failed to generate secrets ({status}): {text}");
        }

        response
            .json()
            .await
            .context("Failed to parse add_generated_secret response")
    }

    /// POST /secrets/update_user_secrets — merge/update secrets with NEP-413 auth
    pub async fn update_user_secrets(
        &self,
        payload: &Value,
    ) -> Result<UpdateUserSecretsResponse> {
        let url = format!("{}/secrets/update_user_secrets", self.base_url);

        let response = self
            .client
            .post(&url)
            .json(payload)
            .send()
            .await
            .context("Failed to call update_user_secrets")?;

        if !response.status().is_success() {
            let status = response.status();
            let text = response.text().await.unwrap_or_default();
            anyhow::bail!("Failed to update secrets ({status}): {text}");
        }

        response
            .json()
            .await
            .context("Failed to parse update_user_secrets response")
    }

    /// POST /secrets/pubkey — get keystore pubkey for encryption.
    ///
    /// `vault_id`, when set, MUST be forwarded to the keystore as
    /// `X-Customer-Vault` so the returned pubkey is derived from the
    /// per-vault master (not the operator default master). Skipping
    /// it produces silent corruption: ciphertext encrypted with the
    /// default-master pubkey is later stored on chain with
    /// `vault_id: ...` binding, the worker derives the vault master
    /// for decrypt, the bytes don't decrypt, the env var is never
    /// injected and the agent reports the secret as missing.
    pub async fn get_secrets_pubkey(
        &self,
        request: &GetPubkeyRequest,
        vault_id: Option<&str>,
    ) -> Result<String> {
        let url = format!("{}/secrets/pubkey", self.base_url);

        let mut req = self.client.post(&url).json(request);
        if let Some(vid) = vault_id {
            req = req.header("X-Customer-Vault", vid);
        }
        let response = req
            .send()
            .await
            .context("Failed to get secrets pubkey")?;

        if !response.status().is_success() {
            let status = response.status();
            let text = response.text().await.unwrap_or_default();
            anyhow::bail!("Failed to get pubkey ({status}): {text}");
        }

        #[derive(Deserialize)]
        struct PubkeyResponse {
            pubkey: String,
        }

        let resp: PubkeyResponse = response
            .json()
            .await
            .context("Failed to parse pubkey response")?;

        Ok(resp.pubkey)
    }

    // ── Payment Check Methods ──────────────────────────────────────────

    /// POST /wallet/v1/payment-check/create
    pub async fn create_payment_check(
        &self,
        api_key: &str,
        token: &str,
        amount: &str,
        memo: Option<&str>,
        expires_in: Option<u64>,
    ) -> Result<PaymentCheckCreateResponse> {
        let url = format!("{}/wallet/v1/payment-check/create", self.base_url);

        let mut body = serde_json::json!({
            "token": token,
            "amount": amount,
        });
        if let Some(memo) = memo {
            body["memo"] = serde_json::Value::String(memo.to_string());
        }
        if let Some(expires_in) = expires_in {
            body["expires_in"] = serde_json::Value::Number(expires_in.into());
        }

        let response = self
            .client
            .post(&url)
            .header("Authorization", format!("Bearer {}", api_key))
            .json(&body)
            .send()
            .await
            .context("Failed to create payment check")?;

        if !response.status().is_success() {
            let status = response.status();
            let text = response.text().await.unwrap_or_default();
            anyhow::bail!("Failed to create payment check ({status}): {text}");
        }

        response
            .json()
            .await
            .context("Failed to parse create check response")
    }

    /// POST /wallet/v1/payment-check/batch-create
    pub async fn batch_create_payment_checks(
        &self,
        api_key: &str,
        checks: &[serde_json::Value],
    ) -> Result<PaymentCheckBatchCreateResponse> {
        let url = format!("{}/wallet/v1/payment-check/batch-create", self.base_url);

        let response = self
            .client
            .post(&url)
            .header("Authorization", format!("Bearer {}", api_key))
            .json(&serde_json::json!({ "checks": checks }))
            .send()
            .await
            .context("Failed to batch create payment checks")?;

        if !response.status().is_success() {
            let status = response.status();
            let text = response.text().await.unwrap_or_default();
            anyhow::bail!("Failed to batch create checks ({status}): {text}");
        }

        response
            .json()
            .await
            .context("Failed to parse batch create response")
    }

    /// POST /wallet/v1/payment-check/claim
    pub async fn claim_payment_check(
        &self,
        api_key: &str,
        check_key: &str,
        amount: Option<&str>,
    ) -> Result<PaymentCheckClaimResponse> {
        let url = format!("{}/wallet/v1/payment-check/claim", self.base_url);

        let mut body = serde_json::json!({ "check_key": check_key });
        if let Some(amount) = amount {
            body["amount"] = serde_json::Value::String(amount.to_string());
        }

        let response = self
            .client
            .post(&url)
            .header("Authorization", format!("Bearer {}", api_key))
            .json(&body)
            .send()
            .await
            .context("Failed to claim payment check")?;

        if !response.status().is_success() {
            let status = response.status();
            let text = response.text().await.unwrap_or_default();
            anyhow::bail!("Failed to claim check ({status}): {text}");
        }

        response
            .json()
            .await
            .context("Failed to parse claim response")
    }

    /// POST /wallet/v1/payment-check/reclaim
    pub async fn reclaim_payment_check(
        &self,
        api_key: &str,
        check_id: &str,
        amount: Option<&str>,
    ) -> Result<PaymentCheckReclaimResponse> {
        let url = format!("{}/wallet/v1/payment-check/reclaim", self.base_url);

        let mut body = serde_json::json!({ "check_id": check_id });
        if let Some(amount) = amount {
            body["amount"] = serde_json::Value::String(amount.to_string());
        }

        let response = self
            .client
            .post(&url)
            .header("Authorization", format!("Bearer {}", api_key))
            .json(&body)
            .send()
            .await
            .context("Failed to reclaim payment check")?;

        if !response.status().is_success() {
            let status = response.status();
            let text = response.text().await.unwrap_or_default();
            anyhow::bail!("Failed to reclaim check ({status}): {text}");
        }

        response
            .json()
            .await
            .context("Failed to parse reclaim response")
    }

    /// GET /wallet/v1/payment-check/status?check_id=...
    pub async fn get_payment_check_status(
        &self,
        api_key: &str,
        check_id: &str,
    ) -> Result<PaymentCheckStatusResponse> {
        let url = format!(
            "{}/wallet/v1/payment-check/status?check_id={}",
            self.base_url, check_id
        );

        let response = self
            .client
            .get(&url)
            .header("Authorization", format!("Bearer {}", api_key))
            .send()
            .await
            .context("Failed to get check status")?;

        if !response.status().is_success() {
            let status = response.status();
            let text = response.text().await.unwrap_or_default();
            anyhow::bail!("Failed to get check status ({status}): {text}");
        }

        response
            .json()
            .await
            .context("Failed to parse check status response")
    }

    /// GET /wallet/v1/payment-check/list
    pub async fn list_payment_checks(
        &self,
        api_key: &str,
        status_filter: Option<&str>,
        limit: i64,
    ) -> Result<PaymentCheckListResponse> {
        let mut url = format!(
            "{}/wallet/v1/payment-check/list?limit={}",
            self.base_url, limit
        );
        if let Some(status) = status_filter {
            url.push_str(&format!("&status={}", status));
        }

        let response = self
            .client
            .get(&url)
            .header("Authorization", format!("Bearer {}", api_key))
            .send()
            .await
            .context("Failed to list payment checks")?;

        if !response.status().is_success() {
            let status = response.status();
            let text = response.text().await.unwrap_or_default();
            anyhow::bail!("Failed to list checks ({status}): {text}");
        }

        response
            .json()
            .await
            .context("Failed to parse check list response")
    }

    /// POST /wallet/v1/sign-message — NEP-413 message signing for external auth
    pub async fn sign_message(
        &self,
        api_key: &str,
        message: &str,
        recipient: &str,
        nonce: Option<&str>,
    ) -> Result<SignMessageResponse> {
        let url = format!("{}/wallet/v1/sign-message", self.base_url);

        let mut body = serde_json::json!({
            "message": message,
            "recipient": recipient,
        });
        if let Some(nonce) = nonce {
            body["nonce"] = serde_json::Value::String(nonce.to_string());
        }

        let response = self
            .client
            .post(&url)
            .header("Authorization", format!("Bearer {}", api_key))
            .json(&body)
            .send()
            .await
            .context("Failed to sign message")?;

        if !response.status().is_success() {
            let status = response.status();
            let text = response.text().await.unwrap_or_default();
            anyhow::bail!("Failed to sign message ({status}): {text}");
        }

        response
            .json()
            .await
            .context("Failed to parse sign message response")
    }

    /// POST /wallet/v1/call — sign and send a NEAR function call via custody wallet
    pub async fn wallet_call(
        &self,
        wallet_key: &str,
        receiver_id: &str,
        method_name: &str,
        args: serde_json::Value,
        gas: u64,
        deposit: u128,
    ) -> Result<WalletCallResponse> {
        let url = format!("{}/wallet/v1/call", self.base_url);

        let body = serde_json::json!({
            "receiver_id": receiver_id,
            "method_name": method_name,
            "args": args,
            "gas": gas.to_string(),
            "deposit": deposit.to_string(),
        });

        let response = self
            .client
            .post(&url)
            .header("Authorization", format!("Bearer {}", wallet_key))
            .json(&body)
            .send()
            .await
            .context("Failed to call wallet API")?;

        if !response.status().is_success() {
            let status = response.status();
            let text = response.text().await.unwrap_or_default();
            anyhow::bail!("Wallet call failed ({status}): {text}");
        }

        response
            .json()
            .await
            .context("Failed to parse wallet call response")
    }

    /// POST /wallet/v1/call with raw (Borsh) args as base64.
    ///
    /// An `onchain_tx_failed` error (HTTP 422) means the tx was broadcast and
    /// is on chain, but its execution reverted. It is returned as
    /// `Ok(status: "failed")` with the real `tx_hash` instead of `Err`, so
    /// callers can decide whether the revert matters (FastFS uploads revert
    /// by design) and never re-broadcast an already-recorded transaction.
    pub async fn wallet_call_raw(
        &self,
        wallet_key: &str,
        receiver_id: &str,
        method_name: &str,
        args_raw: &[u8],
        gas: u64,
        deposit: u128,
    ) -> Result<WalletCallResponse> {
        let url = format!("{}/wallet/v1/call", self.base_url);

        use base64::Engine;
        let args_b64 = base64::engine::general_purpose::STANDARD.encode(args_raw);

        let body = serde_json::json!({
            "receiver_id": receiver_id,
            "method_name": method_name,
            "args_base64": args_b64,
            "gas": gas.to_string(),
            "deposit": deposit.to_string(),
        });

        let response = self
            .client
            .post(&url)
            .header("Authorization", format!("Bearer {}", wallet_key))
            .json(&body)
            .send()
            .await
            .context("Failed to call wallet API")?;

        let status = response.status();
        let text = response.text().await.unwrap_or_default();

        if !status.is_success() {
            if let Ok(err) = serde_json::from_str::<Value>(&text) {
                if err.get("error").and_then(|v| v.as_str()) == Some("onchain_tx_failed") {
                    return Ok(WalletCallResponse {
                        request_id: String::new(),
                        status: "failed".to_string(),
                        tx_hash: err
                            .get("tx_hash")
                            .and_then(|v| v.as_str())
                            .filter(|s| !s.is_empty())
                            .map(String::from),
                        result: err.get("failure").cloned(),
                        approval_id: None,
                    });
                }
            }
            anyhow::bail!("Wallet call failed ({status}): {text}");
        }

        serde_json::from_str(&text).context("Failed to parse wallet call response")
    }

    /// POST /wallet/v1/payment-check/peek
    pub async fn peek_payment_check(
        &self,
        api_key: &str,
        check_key: &str,
    ) -> Result<PaymentCheckPeekResponse> {
        let url = format!("{}/wallet/v1/payment-check/peek", self.base_url);

        let response = self
            .client
            .post(&url)
            .header("Authorization", format!("Bearer {}", api_key))
            .json(&serde_json::json!({ "check_key": check_key }))
            .send()
            .await
            .context("Failed to peek payment check")?;

        if !response.status().is_success() {
            let status = response.status();
            let text = response.text().await.unwrap_or_default();
            anyhow::bail!("Failed to peek check ({status}): {text}");
        }

        response
            .json()
            .await
            .context("Failed to parse peek response")
    }

    // ── Vault init helpers ─────────────────────────────────────────────

    /// `POST /customer/derive-tee-key` — fetch the deterministic TEE
    /// public key the customer must install on their vault during the
    /// atomic deploy. No auth (IP-rate-limited on the coordinator).
    pub async fn derive_vault_tee_key(&self, vault_account_id: &str) -> Result<String> {
        let url = format!("{}/customer/derive-tee-key", self.base_url);
        let response = self
            .client
            .post(&url)
            .json(&serde_json::json!({ "vault_account_id": vault_account_id }))
            .send()
            .await
            .context("Failed to call /customer/derive-tee-key")?;
        if !response.status().is_success() {
            let status = response.status();
            let text = response.text().await.unwrap_or_default();
            anyhow::bail!("derive-tee-key failed ({status}): {text}");
        }
        #[derive(Deserialize)]
        struct Resp {
            public_key: String,
        }
        let resp: Resp = response
            .json()
            .await
            .context("Failed to parse derive-tee-key response")?;
        Ok(resp.public_key)
    }

    /// `POST /customer/sign-verification` — drive
    /// `/sign-vault-verification` on the keystore. Idempotent;
    /// short-circuits if `is_vault_verified == true` already.
    pub async fn sign_vault_verification(
        &self,
        vault_account_id: &str,
    ) -> Result<SignVerificationResponse> {
        let url = format!("{}/customer/sign-verification", self.base_url);
        let response = self
            .client
            .post(&url)
            .json(&serde_json::json!({ "vault_account_id": vault_account_id }))
            .send()
            .await
            .context("Failed to call /customer/sign-verification")?;
        if !response.status().is_success() {
            let status = response.status();
            let text = response.text().await.unwrap_or_default();
            anyhow::bail!("sign-verification failed ({status}): {text}");
        }
        response
            .json()
            .await
            .context("Failed to parse sign-verification response")
    }

}

#[derive(Debug, Deserialize)]
pub struct SignVerificationResponse {
    pub tx_hash: Option<String>,
    pub already_verified: bool,
}

// ── Response Types ─────────────────────────────────────────────────────

#[derive(Debug, Deserialize)]
#[allow(dead_code)]
pub struct PaymentKeyBalanceResponse {
    pub owner: String,
    pub nonce: u32,
    pub initial_balance: String,
    pub spent: String,
    pub reserved: String,
    pub available: String,
    pub last_used_at: Option<String>,
}

#[derive(Debug, Deserialize)]
pub struct PaymentKeyUsageResponse {
    pub usage: Vec<PaymentKeyUsageItem>,
    pub total: i64,
}

#[derive(Debug, Deserialize)]
#[allow(dead_code)]
pub struct PaymentKeyUsageItem {
    pub call_id: String,
    pub project_id: String,
    pub compute_cost: String,
    pub attached_deposit: String,
    pub status: String,
    pub created_at: String,
}

#[derive(Debug, Deserialize)]
#[allow(dead_code)]
pub struct ProjectOwnerEarningsResponse {
    pub project_owner: String,
    pub balance: String,
    pub total_earned: String,
}

#[derive(Debug, Deserialize)]
pub struct EarningsHistoryResponse {
    pub earnings: Vec<EarningRecord>,
    pub total_count: i64,
}

#[derive(Debug, Deserialize)]
pub struct EarningRecord {
    pub project_id: String,
    pub amount: String,
    pub source: String,
    pub created_at: i64,
}

#[derive(Debug, Deserialize)]
pub struct AddGeneratedSecretResponse {
    pub encrypted_data_base64: String,
    #[allow(dead_code)]
    pub all_keys: Vec<String>,
}

#[derive(Debug, Deserialize)]
pub struct UpdateUserSecretsResponse {
    pub encrypted_secrets_base64: String,
}

// ── Sign Message Response Type ────────────────────────────────────────

#[derive(Debug, Deserialize)]
#[allow(dead_code)]
pub struct SignMessageResponse {
    pub account_id: String,
    /// Signature in NEAR format: "ed25519:<base58>"
    pub signature: String,
    /// Signature as raw base64 (NEP-413 standard)
    pub signature_base64: String,
    pub public_key: String,
    pub nonce: String,
}

// ── Wallet Call Response Type ─────────────────────────────────────────

#[derive(Debug, Deserialize)]
#[allow(dead_code)]
pub struct WalletCallResponse {
    pub request_id: String,
    pub status: String,
    pub tx_hash: Option<String>,
    pub result: Option<serde_json::Value>,
    pub approval_id: Option<String>,
}

// ── Payment Check Response Types ──────────────────────────────────────

#[derive(Debug, Deserialize)]
#[allow(dead_code)]
pub struct PaymentCheckCreateResponse {
    pub check_id: String,
    pub check_key: String,
    pub token: String,
    pub amount: String,
    pub memo: Option<String>,
    pub created_at: String,
    pub expires_at: Option<String>,
}

#[derive(Debug, Deserialize)]
pub struct PaymentCheckBatchCreateResponse {
    pub checks: Vec<PaymentCheckCreateResponse>,
}

#[derive(Debug, Deserialize)]
#[allow(dead_code)]
pub struct PaymentCheckClaimResponse {
    pub token: String,
    pub amount_claimed: String,
    pub remaining: String,
    pub memo: Option<String>,
    pub claimed_at: String,
    pub intent_hash: Option<String>,
}

#[derive(Debug, Deserialize)]
#[allow(dead_code)]
pub struct PaymentCheckReclaimResponse {
    pub token: String,
    pub amount_reclaimed: String,
    pub remaining: String,
    pub reclaimed_at: String,
    pub intent_hash: Option<String>,
}

#[derive(Debug, Deserialize)]
#[allow(dead_code)]
pub struct PaymentCheckStatusResponse {
    pub check_id: String,
    pub token: String,
    pub amount: String,
    pub claimed_amount: String,
    pub reclaimed_amount: String,
    pub status: String,
    pub memo: Option<String>,
    pub created_at: String,
    pub expires_at: Option<String>,
    pub claimed_at: Option<String>,
    pub claimed_by: Option<String>,
}

#[derive(Debug, Deserialize)]
pub struct PaymentCheckListResponse {
    pub checks: Vec<PaymentCheckStatusResponse>,
}

#[derive(Debug, Deserialize)]
#[allow(dead_code)]
pub struct PaymentCheckPeekResponse {
    pub token: String,
    pub balance: String,
    pub memo: Option<String>,
    pub status: String,
    pub expires_at: Option<String>,
}