quicknode-sdk 0.1.0

Core library for quicknode 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
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
pub mod webhook;

pub use webhook::{
    ActivateWebhookParams, BitcoinWalletFilterTemplate, CreateWebhookFromTemplateParams,
    EvmAbiFilterTemplate, EvmContractEventsTemplate, EvmWalletFilterTemplate, GetWebhooksParams,
    HyperliquidWalletEventsFilterTemplate, ListWebhooksResponse, SolanaWalletFilterTemplate,
    StellarWalletTransactionsFilterTemplate, TemplateArgs, UpdateWebhookParams,
    UpdateWebhookTemplateParams, Webhook, WebhookDestinationAttributes,
    WebhookEnabledCountResponse, WebhookPageInfo, WebhookStartFrom, WebhookTemplateId,
    XrplWalletFilterTemplate,
};

use crate::{config::WebhooksConfig, errors::SdkError, SdkConfig};

const WEBHOOKS_BASE_URL: &str = "https://api.quicknode.com/webhooks/rest/v1/";

pub(crate) struct ResolvedWebhooksConfig {
    pub(crate) base_url: reqwest::Url,
}

impl ResolvedWebhooksConfig {
    pub(crate) fn from_config(config: Option<&WebhooksConfig>) -> Result<Self, SdkError> {
        let url_str = config
            .and_then(|s| s.base_url.as_deref())
            .unwrap_or(WEBHOOKS_BASE_URL);
        let mut base_url = reqwest::Url::parse(url_str)?;
        if !base_url.path().ends_with('/') {
            base_url.set_path(&format!("{}/", base_url.path()));
        }
        Ok(Self { base_url })
    }
}

// ── Client ─────────────────────────────────────────────────────────────────

/// Client for the Quicknode Webhooks REST API. Create webhooks from filter
/// templates, manage their lifecycle, and update their destinations.
#[derive(Debug, Clone)]
pub struct WebhooksApiClient {
    config: SdkConfig,
}

impl WebhooksApiClient {
    pub fn new(config: SdkConfig) -> Self {
        Self { config }
    }

    /// Returns a paginated list of webhooks on the account. Each entry includes
    /// the webhook's identifier, creation timestamp, name, network, notification
    /// email, destination configuration (URL, security token, compression),
    /// current status, and any associated template. The response also includes
    /// a `pageInfo` object with the applied limit, offset, and total count.
    pub async fn list_webhooks(
        &self,
        params: &GetWebhooksParams,
    ) -> Result<ListWebhooksResponse, SdkError> {
        let mut url = self.config.webhooks().base_url.join("webhooks")?;
        {
            let mut pairs = url.query_pairs_mut();
            if let Some(v) = params.limit {
                pairs.append_pair("limit", &v.to_string());
            }
            if let Some(v) = params.offset {
                pairs.append_pair("offset", &v.to_string());
            }
        }
        let resp = self
            .config
            .http_client()
            .get(url)
            .send()
            .await
            .map_err(SdkError::Http)?;
        let status = resp.status();
        let body = resp.text().await.map_err(SdkError::Http)?;
        if !status.is_success() {
            return Err(SdkError::Api { status, body });
        }
        serde_json::from_str(&body).map_err(|source| SdkError::Decode { source, body })
    }

    /// Removes every webhook on the account. Destructive and takes no
    /// parameters.
    pub async fn delete_all_webhooks(&self) -> Result<(), SdkError> {
        let url = self.config.webhooks().base_url.join("webhooks")?;
        let resp = self
            .config
            .http_client()
            .delete(url)
            .send()
            .await
            .map_err(SdkError::Http)?;
        let status = resp.status();
        if !status.is_success() {
            let body = resp.text().await.map_err(SdkError::Http)?;
            return Err(SdkError::Api { status, body });
        }
        Ok(())
    }

    /// Fetches a single webhook's full configuration and status by ID. Returns
    /// creation timestamp, name, network, notification email, destination
    /// configuration (URL, security token, compression), the sequence number
    /// of the last successfully delivered block, the current status, and the
    /// associated template with its arguments.
    pub async fn get_webhook(&self, id: &str) -> Result<Webhook, SdkError> {
        let url = self
            .config
            .webhooks()
            .base_url
            .join(&format!("webhooks/{id}"))?;
        let resp = self
            .config
            .http_client()
            .get(url)
            .send()
            .await
            .map_err(SdkError::Http)?;
        let status = resp.status();
        let body = resp.text().await.map_err(SdkError::Http)?;
        if !status.is_success() {
            return Err(SdkError::Api { status, body });
        }
        serde_json::from_str(&body).map_err(|source| SdkError::Decode { source, body })
    }

    /// Modifies an existing webhook's configuration. Supports updating the
    /// webhook's name, notification email, and destination attributes (URL,
    /// security token, and compression — `none` or `gzip`). All fields are
    /// optional, so partial updates are supported; if the security token is
    /// omitted on update, one is generated automatically. Returns the
    /// webhook's full updated configuration.
    pub async fn update_webhook(
        &self,
        id: &str,
        params: &UpdateWebhookParams,
    ) -> Result<Webhook, SdkError> {
        let url = self
            .config
            .webhooks()
            .base_url
            .join(&format!("webhooks/{id}"))?;
        let resp = self
            .config
            .http_client()
            .patch(url)
            .json(params)
            .send()
            .await
            .map_err(SdkError::Http)?;
        let status = resp.status();
        let body = resp.text().await.map_err(SdkError::Http)?;
        if !status.is_success() {
            return Err(SdkError::Api { status, body });
        }
        serde_json::from_str(&body).map_err(|source| SdkError::Decode { source, body })
    }

    /// Permanently removes a single webhook by ID.
    pub async fn delete_webhook(&self, id: &str) -> Result<(), SdkError> {
        let url = self
            .config
            .webhooks()
            .base_url
            .join(&format!("webhooks/{id}"))?;
        let resp = self
            .config
            .http_client()
            .delete(url)
            .send()
            .await
            .map_err(SdkError::Http)?;
        let status = resp.status();
        if !status.is_success() {
            let body = resp.text().await.map_err(SdkError::Http)?;
            return Err(SdkError::Api { status, body });
        }
        Ok(())
    }

    /// Pauses a webhook by ID so it stops delivering events until reactivated.
    pub async fn pause_webhook(&self, id: &str) -> Result<(), SdkError> {
        let url = self
            .config
            .webhooks()
            .base_url
            .join(&format!("webhooks/{id}/pause"))?;
        let resp = self
            .config
            .http_client()
            .post(url)
            .send()
            .await
            .map_err(SdkError::Http)?;
        let status = resp.status();
        if !status.is_success() {
            let body = resp.text().await.map_err(SdkError::Http)?;
            return Err(SdkError::Api { status, body });
        }
        Ok(())
    }

    /// Activates a previously created or paused webhook so it begins (or
    /// resumes) delivering events. `start_from` determines where processing
    /// resumes: `Latest` begins from the newest available block; other values
    /// replay from an earlier point.
    pub async fn activate_webhook(
        &self,
        id: &str,
        params: &ActivateWebhookParams,
    ) -> Result<(), SdkError> {
        let url = self
            .config
            .webhooks()
            .base_url
            .join(&format!("webhooks/{id}/activate"))?;
        let resp = self
            .config
            .http_client()
            .post(url)
            .json(params)
            .send()
            .await
            .map_err(SdkError::Http)?;
        let status = resp.status();
        if !status.is_success() {
            let body = resp.text().await.map_err(SdkError::Http)?;
            return Err(SdkError::Api { status, body });
        }
        Ok(())
    }

    /// Returns the total number of enabled webhooks currently configured on
    /// the account.
    pub async fn get_enabled_count(&self) -> Result<WebhookEnabledCountResponse, SdkError> {
        let url = self
            .config
            .webhooks()
            .base_url
            .join("webhooks/enabled_count")?;
        let resp = self
            .config
            .http_client()
            .get(url)
            .send()
            .await
            .map_err(SdkError::Http)?;
        let status = resp.status();
        let body = resp.text().await.map_err(SdkError::Http)?;
        if !status.is_success() {
            return Err(SdkError::Api { status, body });
        }
        serde_json::from_str(&body).map_err(|source| SdkError::Decode { source, body })
    }

    /// Creates a new webhook from a predefined filter template. Requires a
    /// descriptive name, a target blockchain network, and destination
    /// attributes (URL, optional security token — auto-generated when omitted,
    /// and optional compression — `gzip` or `none`). `template_args` carries
    /// template-specific configuration such as wallet addresses or contract
    /// filters. An optional `notification_email` receives alerts if the
    /// webhook terminates.
    pub async fn create_webhook_from_template(
        &self,
        params: &CreateWebhookFromTemplateParams,
    ) -> Result<Webhook, SdkError> {
        let template_id = params.template_args.tag().as_str();
        let url = self
            .config
            .webhooks()
            .base_url
            .join(&format!("webhooks/template/{template_id}"))?;
        let resp = self
            .config
            .http_client()
            .post(url)
            .json(params)
            .send()
            .await
            .map_err(SdkError::Http)?;
        let status = resp.status();
        let body = resp.text().await.map_err(SdkError::Http)?;
        if !status.is_success() {
            return Err(SdkError::Api { status, body });
        }
        serde_json::from_str(&body).map_err(|source| SdkError::Decode { source, body })
    }

    /// Updates an existing template-backed webhook, modifying its template
    /// arguments and optionally its name, notification email, and destination
    /// attributes (URL, security token, compression — `none` or `gzip`).
    /// All optional fields support partial updates; a security token is
    /// generated automatically if not provided. Templates cover EVM chains,
    /// Solana, Bitcoin, XRPL, Hyperliquid, and Stellar.
    pub async fn update_webhook_template(
        &self,
        webhook_id: &str,
        params: &UpdateWebhookTemplateParams,
    ) -> Result<Webhook, SdkError> {
        let template_id = params.template_args.tag().as_str();
        let url = self
            .config
            .webhooks()
            .base_url
            .join(&format!("webhooks/{webhook_id}/template/{template_id}"))?;
        let resp = self
            .config
            .http_client()
            .patch(url)
            .json(params)
            .send()
            .await
            .map_err(SdkError::Http)?;
        let status = resp.status();
        let body = resp.text().await.map_err(SdkError::Http)?;
        if !status.is_success() {
            return Err(SdkError::Api { status, body });
        }
        serde_json::from_str(&body).map_err(|source| SdkError::Decode { source, body })
    }
}

// ── Tests ──────────────────────────────────────────────────────────────────

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
mod tests {
    use super::*;
    use crate::{QuicknodeSdk, SdkFullConfig, WebhooksConfig};
    use wiremock::matchers::{method, path, path_regex};
    use wiremock::{Mock, MockServer, ResponseTemplate};

    fn make_sdk(base_url: String) -> QuicknodeSdk {
        QuicknodeSdk::new(&SdkFullConfig {
            api_key: "test-key".to_string(),
            http: None,
            admin: None,
            streams: None,
            webhooks: Some(WebhooksConfig {
                base_url: Some(base_url),
            }),
            kvstore: None,
        })
        .unwrap()
    }

    fn webhook_response_json() -> serde_json::Value {
        serde_json::json!({
            "id": "wh-1234-5678",
            "name": "test-webhook",
            "status": "active",
            "network": "ethereum-mainnet",
            "created_at": "2026-03-19T12:00:00Z",
            "updated_at": "2026-03-19T12:00:00Z"
        })
    }

    #[tokio::test]
    async fn list_webhooks_success() {
        let server = MockServer::start().await;
        let response = serde_json::json!({
            "data": [webhook_response_json()],
            "pageInfo": {
                "limit": 20,
                "offset": 0,
                "total": 1,
            }
        });
        Mock::given(method("GET"))
            .and(path("/webhooks"))
            .respond_with(ResponseTemplate::new(200).set_body_json(response))
            .mount(&server)
            .await;
        let sdk = make_sdk(format!("{}/", server.uri()));
        let resp = sdk
            .webhooks
            .list_webhooks(&GetWebhooksParams::default())
            .await
            .unwrap();
        assert_eq!(resp.data.len(), 1);
        assert_eq!(resp.data[0].id, "wh-1234-5678");
        assert_eq!(resp.page_info.limit, 20);
        assert_eq!(resp.page_info.offset, 0);
        assert_eq!(resp.page_info.total, 1);
    }

    #[tokio::test]
    async fn list_webhooks_api_error() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/webhooks"))
            .respond_with(ResponseTemplate::new(400).set_body_string("Bad Request"))
            .mount(&server)
            .await;
        let sdk = make_sdk(format!("{}/", server.uri()));
        let err = sdk
            .webhooks
            .list_webhooks(&GetWebhooksParams::default())
            .await
            .unwrap_err();
        assert!(matches!(err, SdkError::Api { .. }));
    }

    #[tokio::test]
    async fn list_webhooks_server_error() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/webhooks"))
            .respond_with(ResponseTemplate::new(500).set_body_string("Internal Server Error"))
            .mount(&server)
            .await;
        let sdk = make_sdk(format!("{}/", server.uri()));
        let err = sdk
            .webhooks
            .list_webhooks(&GetWebhooksParams::default())
            .await
            .unwrap_err();
        assert!(matches!(err, SdkError::Api { .. }));
    }

    #[tokio::test]
    async fn get_webhook_success() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/webhooks/test-id"))
            .respond_with(ResponseTemplate::new(200).set_body_json(webhook_response_json()))
            .mount(&server)
            .await;
        let sdk = make_sdk(format!("{}/", server.uri()));
        let resp = sdk.webhooks.get_webhook("test-id").await.unwrap();
        assert_eq!(resp.id, "wh-1234-5678");
    }

    #[tokio::test]
    async fn get_webhook_api_error() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/webhooks/test-id"))
            .respond_with(ResponseTemplate::new(404).set_body_string("Not Found"))
            .mount(&server)
            .await;
        let sdk = make_sdk(format!("{}/", server.uri()));
        let err = sdk.webhooks.get_webhook("test-id").await.unwrap_err();
        assert!(matches!(err, SdkError::Api { .. }));
    }

    #[tokio::test]
    async fn update_webhook_success() {
        let server = MockServer::start().await;
        let mut updated = webhook_response_json();
        updated["name"] = serde_json::json!("updated-name");
        Mock::given(method("PATCH"))
            .and(path("/webhooks/test-id"))
            .respond_with(ResponseTemplate::new(200).set_body_json(updated))
            .mount(&server)
            .await;
        let sdk = make_sdk(format!("{}/", server.uri()));
        let params = UpdateWebhookParams {
            name: Some("updated-name".to_string()),
            ..Default::default()
        };
        let resp = sdk
            .webhooks
            .update_webhook("test-id", &params)
            .await
            .unwrap();
        assert_eq!(resp.name, "updated-name");
    }

    #[tokio::test]
    async fn update_webhook_api_error() {
        let server = MockServer::start().await;
        Mock::given(method("PATCH"))
            .and(path("/webhooks/test-id"))
            .respond_with(ResponseTemplate::new(400).set_body_string("Bad Request"))
            .mount(&server)
            .await;
        let sdk = make_sdk(format!("{}/", server.uri()));
        let params = UpdateWebhookParams::default();
        let err = sdk
            .webhooks
            .update_webhook("test-id", &params)
            .await
            .unwrap_err();
        assert!(matches!(err, SdkError::Api { .. }));
    }

    #[tokio::test]
    async fn delete_webhook_success() {
        let server = MockServer::start().await;
        Mock::given(method("DELETE"))
            .and(path("/webhooks/test-id"))
            .respond_with(ResponseTemplate::new(200))
            .mount(&server)
            .await;
        let sdk = make_sdk(format!("{}/", server.uri()));
        sdk.webhooks.delete_webhook("test-id").await.unwrap();
    }

    #[tokio::test]
    async fn delete_webhook_api_error() {
        let server = MockServer::start().await;
        Mock::given(method("DELETE"))
            .and(path("/webhooks/test-id"))
            .respond_with(ResponseTemplate::new(404).set_body_string("Not Found"))
            .mount(&server)
            .await;
        let sdk = make_sdk(format!("{}/", server.uri()));
        let err = sdk.webhooks.delete_webhook("test-id").await.unwrap_err();
        assert!(matches!(err, SdkError::Api { .. }));
    }

    #[tokio::test]
    async fn delete_all_webhooks_success() {
        let server = MockServer::start().await;
        Mock::given(method("DELETE"))
            .and(path("/webhooks"))
            .respond_with(ResponseTemplate::new(204))
            .mount(&server)
            .await;
        let sdk = make_sdk(format!("{}/", server.uri()));
        sdk.webhooks.delete_all_webhooks().await.unwrap();
    }

    #[tokio::test]
    async fn delete_all_webhooks_api_error() {
        let server = MockServer::start().await;
        Mock::given(method("DELETE"))
            .and(path("/webhooks"))
            .respond_with(ResponseTemplate::new(400).set_body_string("Bad Request"))
            .mount(&server)
            .await;
        let sdk = make_sdk(format!("{}/", server.uri()));
        let err = sdk.webhooks.delete_all_webhooks().await.unwrap_err();
        assert!(matches!(err, SdkError::Api { .. }));
    }

    #[tokio::test]
    async fn pause_webhook_success() {
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/webhooks/test-id/pause"))
            .respond_with(ResponseTemplate::new(201))
            .mount(&server)
            .await;
        let sdk = make_sdk(format!("{}/", server.uri()));
        sdk.webhooks.pause_webhook("test-id").await.unwrap();
    }

    #[tokio::test]
    async fn pause_webhook_api_error() {
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/webhooks/test-id/pause"))
            .respond_with(ResponseTemplate::new(404).set_body_string("Not Found"))
            .mount(&server)
            .await;
        let sdk = make_sdk(format!("{}/", server.uri()));
        let err = sdk.webhooks.pause_webhook("test-id").await.unwrap_err();
        assert!(matches!(err, SdkError::Api { .. }));
    }

    #[tokio::test]
    async fn activate_webhook_success() {
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/webhooks/test-id/activate"))
            .respond_with(ResponseTemplate::new(201))
            .mount(&server)
            .await;
        let sdk = make_sdk(format!("{}/", server.uri()));
        let params = ActivateWebhookParams {
            start_from: WebhookStartFrom::Latest,
        };
        sdk.webhooks
            .activate_webhook("test-id", &params)
            .await
            .unwrap();
    }

    #[tokio::test]
    async fn activate_webhook_api_error() {
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/webhooks/test-id/activate"))
            .respond_with(ResponseTemplate::new(400).set_body_string("Bad Request"))
            .mount(&server)
            .await;
        let sdk = make_sdk(format!("{}/", server.uri()));
        let params = ActivateWebhookParams {
            start_from: WebhookStartFrom::Latest,
        };
        let err = sdk
            .webhooks
            .activate_webhook("test-id", &params)
            .await
            .unwrap_err();
        assert!(matches!(err, SdkError::Api { .. }));
    }

    #[tokio::test]
    async fn get_enabled_count_success() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/webhooks/enabled_count"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({"total": 5})))
            .mount(&server)
            .await;
        let sdk = make_sdk(format!("{}/", server.uri()));
        let resp = sdk.webhooks.get_enabled_count().await.unwrap();
        assert_eq!(resp.total, 5);
    }

    #[tokio::test]
    async fn get_enabled_count_api_error() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/webhooks/enabled_count"))
            .respond_with(ResponseTemplate::new(400).set_body_string("Bad Request"))
            .mount(&server)
            .await;
        let sdk = make_sdk(format!("{}/", server.uri()));
        let err = sdk.webhooks.get_enabled_count().await.unwrap_err();
        assert!(matches!(err, SdkError::Api { .. }));
    }

    #[tokio::test]
    async fn create_webhook_from_template_success() {
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path_regex("/webhooks/template/evmWalletFilter"))
            .respond_with(ResponseTemplate::new(201).set_body_json(webhook_response_json()))
            .mount(&server)
            .await;
        let sdk = make_sdk(format!("{}/", server.uri()));
        let template_args = TemplateArgs::EvmWalletFilter(EvmWalletFilterTemplate {
            wallets: vec!["0xabc".to_string()],
        });
        let params = CreateWebhookFromTemplateParams {
            name: "test-webhook".to_string(),
            network: "ethereum-mainnet".to_string(),
            notification_email: None,
            destination_attributes: WebhookDestinationAttributes {
                url: "https://example.com/hook".to_string(),
                security_token: None,
                compression: None,
            },
            template_args,
        };
        let resp = sdk
            .webhooks
            .create_webhook_from_template(&params)
            .await
            .unwrap();
        assert_eq!(resp.id, "wh-1234-5678");
    }

    #[tokio::test]
    async fn create_webhook_from_template_api_error() {
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path_regex("/webhooks/template/evmWalletFilter"))
            .respond_with(ResponseTemplate::new(400).set_body_string("Bad Request"))
            .mount(&server)
            .await;
        let sdk = make_sdk(format!("{}/", server.uri()));
        let template_args = TemplateArgs::EvmWalletFilter(EvmWalletFilterTemplate {
            wallets: vec!["0xabc".to_string()],
        });
        let params = CreateWebhookFromTemplateParams {
            name: "test-webhook".to_string(),
            network: "ethereum-mainnet".to_string(),
            notification_email: None,
            destination_attributes: WebhookDestinationAttributes {
                url: "https://example.com/hook".to_string(),
                security_token: None,
                compression: None,
            },
            template_args,
        };
        let err = sdk
            .webhooks
            .create_webhook_from_template(&params)
            .await
            .unwrap_err();
        assert!(matches!(err, SdkError::Api { .. }));
    }

    #[tokio::test]
    async fn update_webhook_template_success() {
        let server = MockServer::start().await;
        Mock::given(method("PATCH"))
            .and(path_regex("/webhooks/test-id/template/evmWalletFilter"))
            .respond_with(ResponseTemplate::new(200).set_body_json(webhook_response_json()))
            .mount(&server)
            .await;
        let sdk = make_sdk(format!("{}/", server.uri()));
        let template_args = TemplateArgs::EvmWalletFilter(EvmWalletFilterTemplate {
            wallets: vec!["0xabc".to_string()],
        });
        let params = UpdateWebhookTemplateParams {
            name: None,
            notification_email: None,
            destination_attributes: None,
            template_args,
        };
        let resp = sdk
            .webhooks
            .update_webhook_template("test-id", &params)
            .await
            .unwrap();
        assert_eq!(resp.id, "wh-1234-5678");
    }

    // Wire-inspection regression: confirm that `name` reaches the wire when
    // supplied so any future serde rename/drop of the field fails loudly.
    #[tokio::test]
    async fn update_webhook_template_wire_body_includes_name() {
        use wiremock::matchers::body_partial_json;
        let server = MockServer::start().await;
        Mock::given(method("PATCH"))
            .and(path_regex("/webhooks/test-id/template/evmWalletFilter"))
            .and(body_partial_json(serde_json::json!({"name": "new-name"})))
            .respond_with(ResponseTemplate::new(200).set_body_json(webhook_response_json()))
            .mount(&server)
            .await;
        let sdk = make_sdk(format!("{}/", server.uri()));
        let template_args = TemplateArgs::EvmWalletFilter(EvmWalletFilterTemplate {
            wallets: vec!["0xabc".to_string()],
        });
        let params = UpdateWebhookTemplateParams {
            name: Some("new-name".to_string()),
            notification_email: None,
            destination_attributes: None,
            template_args,
        };
        sdk.webhooks
            .update_webhook_template("test-id", &params)
            .await
            .unwrap();
    }

    // Wire-inspection regression: the API expects `eventHashes` (camelCase)
    // and returns 500 if it sees `event_hashes`. Confirm the field reaches the
    // wire under the camelCase key.
    #[tokio::test]
    async fn create_webhook_from_template_wire_body_uses_camelcase_event_hashes() {
        use wiremock::matchers::body_partial_json;
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path_regex("/webhooks/template/evmContractEvents"))
            .and(body_partial_json(serde_json::json!({
                "templateArgs": {
                    "eventHashes": ["0xabcd"],
                }
            })))
            .respond_with(ResponseTemplate::new(201).set_body_json(webhook_response_json()))
            .mount(&server)
            .await;
        let sdk = make_sdk(format!("{}/", server.uri()));
        let template_args = TemplateArgs::EvmContractEvents(EvmContractEventsTemplate {
            contracts: vec!["0xa0b8".to_string()],
            event_hashes: Some(vec!["0xabcd".to_string()]),
        });
        let params = CreateWebhookFromTemplateParams {
            name: "test-webhook".to_string(),
            network: "ethereum-mainnet".to_string(),
            notification_email: None,
            destination_attributes: WebhookDestinationAttributes {
                url: "https://example.com/hook".to_string(),
                security_token: None,
                compression: None,
            },
            template_args,
        };
        sdk.webhooks
            .create_webhook_from_template(&params)
            .await
            .unwrap();
    }

    #[tokio::test]
    async fn update_webhook_template_api_error() {
        let server = MockServer::start().await;
        Mock::given(method("PATCH"))
            .and(path_regex("/webhooks/test-id/template/evmWalletFilter"))
            .respond_with(ResponseTemplate::new(400).set_body_string("Bad Request"))
            .mount(&server)
            .await;
        let sdk = make_sdk(format!("{}/", server.uri()));
        let template_args = TemplateArgs::EvmWalletFilter(EvmWalletFilterTemplate {
            wallets: vec!["0xabc".to_string()],
        });
        let params = UpdateWebhookTemplateParams {
            name: None,
            notification_email: None,
            destination_attributes: None,
            template_args,
        };
        let err = sdk
            .webhooks
            .update_webhook_template("test-id", &params)
            .await
            .unwrap_err();
        assert!(matches!(err, SdkError::Api { .. }));
    }
}