quicknode-sdk 0.4.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
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
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
#[cfg(feature = "rust")]
use bon::Builder;
#[cfg(feature = "node")]
use napi_derive::napi;
#[cfg(feature = "python")]
use pyo3::{pyclass, pymethods};
#[cfg(feature = "python")]
use pyo3_stub_gen::derive::{gen_stub_pyclass, gen_stub_pymethods};
use serde::{Deserialize, Deserializer, Serialize};

fn deserialize_as_optional_json_string<'de, D>(deserializer: D) -> Result<Option<String>, D::Error>
where
    D: Deserializer<'de>,
{
    let value = Option::<serde_json::Value>::deserialize(deserializer)?;
    match value {
        None => Ok(None),
        Some(v) => serde_json::to_string(&v)
            .map(Some)
            .map_err(serde::de::Error::custom),
    }
}

// ── Enums ──────────────────────────────────────────────────────────────────

/// Identifier of a predefined webhook filter template.
#[cfg_attr(feature = "node", napi(string_enum))]
#[cfg_attr(not(feature = "node"), derive(Clone))]
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum WebhookTemplateId {
    EvmWalletFilter,
    EvmContractEvents,
    EvmAbiFilter,
    SolanaWalletFilter,
    BitcoinWalletFilter,
    XrplWalletFilter,
    HyperliquidWalletEventsFilter,
    StellarWalletTransactionsSourceAccountFilter,
}

impl WebhookTemplateId {
    pub fn as_str(&self) -> &'static str {
        match self {
            WebhookTemplateId::EvmWalletFilter => "evmWalletFilter",
            WebhookTemplateId::EvmContractEvents => "evmContractEvents",
            WebhookTemplateId::EvmAbiFilter => "evmAbiFilter",
            WebhookTemplateId::SolanaWalletFilter => "solanaWalletFilter",
            WebhookTemplateId::BitcoinWalletFilter => "bitcoinWalletFilter",
            WebhookTemplateId::XrplWalletFilter => "xrplWalletFilter",
            WebhookTemplateId::HyperliquidWalletEventsFilter => "hyperliquidWalletEventsFilter",
            WebhookTemplateId::StellarWalletTransactionsSourceAccountFilter => {
                "stellarWalletTransactionsSourceAccountFilter"
            }
        }
    }
}

/// Position a webhook begins (or resumes) delivering from when activated.
#[cfg_attr(feature = "node", napi(string_enum))]
#[cfg_attr(not(feature = "node"), derive(Clone))]
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum WebhookStartFrom {
    /// Resume from the last-delivered block.
    Last,
    /// Start from the newest available block.
    Latest,
}

// ── Template Arg Structs ───────────────────────────────────────────────────

/// Template arguments for an EVM wallet filter: matches activity for a list of
/// wallet addresses.
#[cfg_attr(feature = "rust", derive(Builder))]
#[cfg_attr(feature = "python", gen_stub_pyclass)]
#[cfg_attr(feature = "python", pyclass(get_all, set_all))]
#[cfg_attr(feature = "node", napi(object))]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EvmWalletFilterTemplate {
    /// Wallet addresses to match against.
    pub wallets: Vec<String>,
}

#[cfg(feature = "python")]
#[gen_stub_pymethods]
#[pymethods]
impl EvmWalletFilterTemplate {
    #[new]
    pub fn new(wallets: Vec<String>) -> Self {
        Self { wallets }
    }
}

/// Template arguments for filtering EVM contract events, scoped to a specific
/// set of event topic hashes.
#[cfg_attr(feature = "rust", derive(Builder))]
#[cfg_attr(feature = "python", gen_stub_pyclass)]
#[cfg_attr(feature = "python", pyclass(get_all, set_all))]
#[cfg_attr(feature = "node", napi(object))]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct EvmContractEventsTemplate {
    /// Contract addresses to watch for events.
    pub contracts: Vec<String>,
    /// Event topic hashes to restrict the filter to specific events.
    pub event_hashes: Vec<String>,
}

#[cfg(feature = "python")]
#[gen_stub_pymethods]
#[pymethods]
impl EvmContractEventsTemplate {
    #[new]
    pub fn new(contracts: Vec<String>, event_hashes: Vec<String>) -> Self {
        Self {
            contracts,
            event_hashes,
        }
    }
}

/// Template arguments for an EVM ABI filter: decodes and filters events for a
/// set of contracts using a provided ABI.
#[cfg_attr(feature = "rust", derive(Builder))]
#[cfg_attr(feature = "python", gen_stub_pyclass)]
#[cfg_attr(feature = "python", pyclass(get_all, set_all))]
#[cfg_attr(feature = "node", napi(object))]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EvmAbiFilterTemplate {
    /// JSON-encoded contract ABI used to decode event data.
    pub abi: String,
    /// Contract addresses to watch for events.
    pub contracts: Vec<String>,
}

#[cfg(feature = "python")]
#[gen_stub_pymethods]
#[pymethods]
impl EvmAbiFilterTemplate {
    #[new]
    pub fn new(abi: String, contracts: Vec<String>) -> Self {
        Self { abi, contracts }
    }
}

/// Template arguments for a Solana wallet filter: matches activity for a list
/// of Solana account addresses.
#[cfg_attr(feature = "rust", derive(Builder))]
#[cfg_attr(feature = "python", gen_stub_pyclass)]
#[cfg_attr(feature = "python", pyclass(get_all, set_all))]
#[cfg_attr(feature = "node", napi(object))]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SolanaWalletFilterTemplate {
    /// Solana account addresses to match against.
    pub accounts: Vec<String>,
}

#[cfg(feature = "python")]
#[gen_stub_pymethods]
#[pymethods]
impl SolanaWalletFilterTemplate {
    #[new]
    pub fn new(accounts: Vec<String>) -> Self {
        Self { accounts }
    }
}

/// Template arguments for a Bitcoin wallet filter.
#[cfg_attr(feature = "rust", derive(Builder))]
#[cfg_attr(feature = "python", gen_stub_pyclass)]
#[cfg_attr(feature = "python", pyclass(get_all, set_all))]
#[cfg_attr(feature = "node", napi(object))]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BitcoinWalletFilterTemplate {
    /// Bitcoin wallet addresses to match against.
    pub wallets: Vec<String>,
}

#[cfg(feature = "python")]
#[gen_stub_pymethods]
#[pymethods]
impl BitcoinWalletFilterTemplate {
    #[new]
    pub fn new(wallets: Vec<String>) -> Self {
        Self { wallets }
    }
}

/// Template arguments for an XRPL wallet filter.
#[cfg_attr(feature = "rust", derive(Builder))]
#[cfg_attr(feature = "python", gen_stub_pyclass)]
#[cfg_attr(feature = "python", pyclass(get_all, set_all))]
#[cfg_attr(feature = "node", napi(object))]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct XrplWalletFilterTemplate {
    /// XRPL wallet addresses to match against.
    pub wallets: Vec<String>,
}

#[cfg(feature = "python")]
#[gen_stub_pymethods]
#[pymethods]
impl XrplWalletFilterTemplate {
    #[new]
    pub fn new(wallets: Vec<String>) -> Self {
        Self { wallets }
    }
}

/// Template arguments for a Hyperliquid wallet-events filter.
#[cfg_attr(feature = "rust", derive(Builder))]
#[cfg_attr(feature = "python", gen_stub_pyclass)]
#[cfg_attr(feature = "python", pyclass(get_all, set_all))]
#[cfg_attr(feature = "node", napi(object))]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HyperliquidWalletEventsFilterTemplate {
    /// Hyperliquid wallet addresses to match against.
    pub wallets: Vec<String>,
}

#[cfg(feature = "python")]
#[gen_stub_pymethods]
#[pymethods]
impl HyperliquidWalletEventsFilterTemplate {
    #[new]
    pub fn new(wallets: Vec<String>) -> Self {
        Self { wallets }
    }
}

/// Template arguments for a Stellar wallet-transactions filter, matching
/// transactions where the given wallets are the source account.
#[cfg_attr(feature = "rust", derive(Builder))]
#[cfg_attr(feature = "python", gen_stub_pyclass)]
#[cfg_attr(feature = "python", pyclass(get_all, set_all))]
#[cfg_attr(feature = "node", napi(object))]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StellarWalletTransactionsFilterTemplate {
    /// Stellar wallet addresses to match against.
    pub wallets: Vec<String>,
}

#[cfg(feature = "python")]
#[gen_stub_pymethods]
#[pymethods]
impl StellarWalletTransactionsFilterTemplate {
    #[new]
    pub fn new(wallets: Vec<String>) -> Self {
        Self { wallets }
    }
}

// ── ByList Template Arg Structs ────────────────────────────────────────────
//
// Every template supports two input shapes: inline values (e.g. `wallets:
// [...]`) or a reference to a pre-created list (`walletsListName: "..."`).
// The two shapes share the same `templateId` and the same URL path; the
// server disambiguates by which field is present. The SDK models each shape
// as its own struct so callers can't accidentally mix them.

/// ByList form of `EvmWalletFilterTemplate` — references a pre-created
/// wallets list by name instead of inlining the addresses.
#[cfg_attr(feature = "rust", derive(Builder))]
#[cfg_attr(feature = "python", gen_stub_pyclass)]
#[cfg_attr(feature = "python", pyclass(get_all, set_all))]
#[cfg_attr(feature = "node", napi(object))]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct EvmWalletFilterByListTemplate {
    /// Name of the pre-created wallets list.
    pub wallets_list_name: String,
}

#[cfg(feature = "python")]
#[gen_stub_pymethods]
#[pymethods]
impl EvmWalletFilterByListTemplate {
    #[new]
    pub fn new(wallets_list_name: String) -> Self {
        Self { wallets_list_name }
    }
}

/// ByList form of `EvmContractEventsTemplate` — references pre-created
/// contract and (optionally) event-hash lists by name. Omitting
/// `event_hashes_list_name` matches all events from the listed contracts.
#[cfg_attr(feature = "rust", derive(Builder))]
#[cfg_attr(feature = "python", gen_stub_pyclass)]
#[cfg_attr(feature = "python", pyclass(get_all, set_all))]
#[cfg_attr(feature = "node", napi(object))]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct EvmContractEventsByListTemplate {
    /// Name of the pre-created contracts list.
    pub contracts_list_name: String,
    /// Optional name of a pre-created event-hashes list; when omitted, all
    /// events from the listed contracts match.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub event_hashes_list_name: Option<String>,
}

#[cfg(feature = "python")]
#[gen_stub_pymethods]
#[pymethods]
impl EvmContractEventsByListTemplate {
    #[new]
    #[pyo3(signature = (contracts_list_name, event_hashes_list_name=None))]
    pub fn new(contracts_list_name: String, event_hashes_list_name: Option<String>) -> Self {
        Self {
            contracts_list_name,
            event_hashes_list_name,
        }
    }
}

/// ByList form of `EvmAbiFilterTemplate` — carries the ABI inline (the only
/// non-list shape this template has) and optionally references a pre-created
/// contracts list. Note the wire key is `abiJson`, distinct from the inline
/// variant's `abi`.
#[cfg_attr(feature = "rust", derive(Builder))]
#[cfg_attr(feature = "python", gen_stub_pyclass)]
#[cfg_attr(feature = "python", pyclass(get_all, set_all))]
#[cfg_attr(feature = "node", napi(object))]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct EvmAbiFilterByListTemplate {
    /// JSON-encoded contract ABI used to decode event data.
    pub abi_json: String,
    /// Optional name of a pre-created contracts list; when omitted, the ABI
    /// is applied to all contracts.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub contracts_list_name: Option<String>,
}

#[cfg(feature = "python")]
#[gen_stub_pymethods]
#[pymethods]
impl EvmAbiFilterByListTemplate {
    #[new]
    #[pyo3(signature = (abi_json, contracts_list_name=None))]
    pub fn new(abi_json: String, contracts_list_name: Option<String>) -> Self {
        Self {
            abi_json,
            contracts_list_name,
        }
    }
}

/// ByList form of `SolanaWalletFilterTemplate`.
#[cfg_attr(feature = "rust", derive(Builder))]
#[cfg_attr(feature = "python", gen_stub_pyclass)]
#[cfg_attr(feature = "python", pyclass(get_all, set_all))]
#[cfg_attr(feature = "node", napi(object))]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SolanaWalletFilterByListTemplate {
    /// Name of the pre-created accounts list.
    pub accounts_list_name: String,
}

#[cfg(feature = "python")]
#[gen_stub_pymethods]
#[pymethods]
impl SolanaWalletFilterByListTemplate {
    #[new]
    pub fn new(accounts_list_name: String) -> Self {
        Self { accounts_list_name }
    }
}

/// ByList form of `BitcoinWalletFilterTemplate`.
#[cfg_attr(feature = "rust", derive(Builder))]
#[cfg_attr(feature = "python", gen_stub_pyclass)]
#[cfg_attr(feature = "python", pyclass(get_all, set_all))]
#[cfg_attr(feature = "node", napi(object))]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BitcoinWalletFilterByListTemplate {
    /// Name of the pre-created wallets list.
    pub wallets_list_name: String,
}

#[cfg(feature = "python")]
#[gen_stub_pymethods]
#[pymethods]
impl BitcoinWalletFilterByListTemplate {
    #[new]
    pub fn new(wallets_list_name: String) -> Self {
        Self { wallets_list_name }
    }
}

/// ByList form of `XrplWalletFilterTemplate`.
#[cfg_attr(feature = "rust", derive(Builder))]
#[cfg_attr(feature = "python", gen_stub_pyclass)]
#[cfg_attr(feature = "python", pyclass(get_all, set_all))]
#[cfg_attr(feature = "node", napi(object))]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct XrplWalletFilterByListTemplate {
    /// Name of the pre-created wallets list.
    pub wallets_list_name: String,
}

#[cfg(feature = "python")]
#[gen_stub_pymethods]
#[pymethods]
impl XrplWalletFilterByListTemplate {
    #[new]
    pub fn new(wallets_list_name: String) -> Self {
        Self { wallets_list_name }
    }
}

/// ByList form of `HyperliquidWalletEventsFilterTemplate`.
#[cfg_attr(feature = "rust", derive(Builder))]
#[cfg_attr(feature = "python", gen_stub_pyclass)]
#[cfg_attr(feature = "python", pyclass(get_all, set_all))]
#[cfg_attr(feature = "node", napi(object))]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct HyperliquidWalletEventsFilterByListTemplate {
    /// Name of the pre-created wallets list.
    pub wallets_list_name: String,
}

#[cfg(feature = "python")]
#[gen_stub_pymethods]
#[pymethods]
impl HyperliquidWalletEventsFilterByListTemplate {
    #[new]
    pub fn new(wallets_list_name: String) -> Self {
        Self { wallets_list_name }
    }
}

/// ByList form of `StellarWalletTransactionsFilterTemplate`.
#[cfg_attr(feature = "rust", derive(Builder))]
#[cfg_attr(feature = "python", gen_stub_pyclass)]
#[cfg_attr(feature = "python", pyclass(get_all, set_all))]
#[cfg_attr(feature = "node", napi(object))]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct StellarWalletTransactionsFilterByListTemplate {
    /// Name of the pre-created wallets list.
    pub wallets_list_name: String,
}

#[cfg(feature = "python")]
#[gen_stub_pymethods]
#[pymethods]
impl StellarWalletTransactionsFilterByListTemplate {
    #[new]
    pub fn new(wallets_list_name: String) -> Self {
        Self { wallets_list_name }
    }
}

// ── Per-template Inline-or-ByList enums ────────────────────────────────────
//
// `#[serde(untagged)]` dispatches on field shape — inline and ByList structs
// have disjoint field names so deserialization is unambiguous.

/// `EvmWalletFilter` template arguments in either inline or by-list form.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum EvmWalletFilterInput {
    Inline(EvmWalletFilterTemplate),
    ByList(EvmWalletFilterByListTemplate),
}

/// `EvmContractEvents` template arguments in either inline or by-list form.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum EvmContractEventsInput {
    Inline(EvmContractEventsTemplate),
    ByList(EvmContractEventsByListTemplate),
}

/// `EvmAbiFilter` template arguments in either inline or by-list form.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum EvmAbiFilterInput {
    Inline(EvmAbiFilterTemplate),
    ByList(EvmAbiFilterByListTemplate),
}

/// `SolanaWalletFilter` template arguments in either inline or by-list form.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum SolanaWalletFilterInput {
    Inline(SolanaWalletFilterTemplate),
    ByList(SolanaWalletFilterByListTemplate),
}

/// `BitcoinWalletFilter` template arguments in either inline or by-list form.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum BitcoinWalletFilterInput {
    Inline(BitcoinWalletFilterTemplate),
    ByList(BitcoinWalletFilterByListTemplate),
}

/// `XrplWalletFilter` template arguments in either inline or by-list form.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum XrplWalletFilterInput {
    Inline(XrplWalletFilterTemplate),
    ByList(XrplWalletFilterByListTemplate),
}

/// `HyperliquidWalletEventsFilter` template arguments in either inline or by-list form.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum HyperliquidWalletEventsFilterInput {
    Inline(HyperliquidWalletEventsFilterTemplate),
    ByList(HyperliquidWalletEventsFilterByListTemplate),
}

/// `StellarWalletTransactionsSourceAccountFilter` template arguments in
/// either inline or by-list form.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum StellarWalletTransactionsFilterInput {
    Inline(StellarWalletTransactionsFilterTemplate),
    ByList(StellarWalletTransactionsFilterByListTemplate),
}

// ── Template Args ──────────────────────────────────────────────────────────

/// Template identifier paired with its arguments. Exactly one variant selects
/// which filter is applied; each variant's inner enum picks between inline
/// values and a list reference. Consumed by `create_webhook_from_template`
/// and `update_webhook_template`.
// Pure-Rust discriminated union; no #[pyclass] / #[napi(object)] because PyO3
// and napi-rs cannot represent enum-with-data. Each language binding crate
// wraps this type for its own FFI surface.
// The serde tag/content pair matches the API wire format when flattened into
// a request struct.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "templateId", content = "templateArgs", rename_all = "camelCase")]
pub enum TemplateArgs {
    /// EVM wallet filter.
    EvmWalletFilter(EvmWalletFilterInput),
    /// EVM contract events filter.
    EvmContractEvents(EvmContractEventsInput),
    /// EVM ABI filter.
    EvmAbiFilter(EvmAbiFilterInput),
    /// Solana wallet filter.
    SolanaWalletFilter(SolanaWalletFilterInput),
    /// Bitcoin wallet filter.
    BitcoinWalletFilter(BitcoinWalletFilterInput),
    /// XRPL wallet filter.
    XrplWalletFilter(XrplWalletFilterInput),
    /// Hyperliquid wallet-events filter.
    HyperliquidWalletEventsFilter(HyperliquidWalletEventsFilterInput),
    /// Stellar wallet-transactions filter (source-account match).
    StellarWalletTransactionsSourceAccountFilter(StellarWalletTransactionsFilterInput),
}

impl TemplateArgs {
    pub fn tag(&self) -> WebhookTemplateId {
        match self {
            Self::EvmWalletFilter(_) => WebhookTemplateId::EvmWalletFilter,
            Self::EvmContractEvents(_) => WebhookTemplateId::EvmContractEvents,
            Self::EvmAbiFilter(_) => WebhookTemplateId::EvmAbiFilter,
            Self::SolanaWalletFilter(_) => WebhookTemplateId::SolanaWalletFilter,
            Self::BitcoinWalletFilter(_) => WebhookTemplateId::BitcoinWalletFilter,
            Self::XrplWalletFilter(_) => WebhookTemplateId::XrplWalletFilter,
            Self::HyperliquidWalletEventsFilter(_) => {
                WebhookTemplateId::HyperliquidWalletEventsFilter
            }
            Self::StellarWalletTransactionsSourceAccountFilter(_) => {
                WebhookTemplateId::StellarWalletTransactionsSourceAccountFilter
            }
        }
    }
}

// ── Webhook Destination Attributes ─────────────────────────────────────────

/// Destination configuration for a webhook.
#[cfg_attr(feature = "python", gen_stub_pyclass)]
#[cfg_attr(feature = "python", pyclass(get_all, set_all))]
#[cfg_attr(feature = "node", napi(object))]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WebhookDestinationAttributes {
    /// Target URL that receives webhook payloads.
    pub url: String,
    /// Optional token sent with each payload so the receiver can verify authenticity; generated automatically when omitted.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub security_token: Option<String>,
    /// Payload compression (`gzip` or `none`).
    pub compression: String,
}

#[cfg(feature = "python")]
#[gen_stub_pymethods]
#[pymethods]
impl WebhookDestinationAttributes {
    #[new]
    #[pyo3(signature = (url, compression, security_token=None))]
    pub fn new(url: String, compression: String, security_token: Option<String>) -> Self {
        Self {
            url,
            security_token,
            compression,
        }
    }
}

// ── Request Types ──────────────────────────────────────────────────────────

/// Parameters for `list_webhooks`.
#[cfg_attr(feature = "python", gen_stub_pyclass)]
#[cfg_attr(feature = "python", pyclass(get_all, set_all))]
#[cfg_attr(feature = "node", napi(object))]
#[cfg_attr(not(feature = "node"), derive(Clone))]
#[derive(Debug, Default, Serialize, Deserialize)]
pub struct GetWebhooksParams {
    /// Maximum number of webhooks returned.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub limit: Option<i64>,
    /// Starting index into the result set.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub offset: Option<i64>,
}

#[cfg(feature = "python")]
#[gen_stub_pymethods]
#[pymethods]
impl GetWebhooksParams {
    #[new]
    #[pyo3(signature = (limit=None, offset=None))]
    pub fn new(limit: Option<i64>, offset: Option<i64>) -> Self {
        Self { limit, offset }
    }
}

/// Parameters for `update_webhook`. All fields are optional; only set fields
/// are modified.
#[cfg_attr(feature = "python", gen_stub_pyclass)]
#[cfg_attr(feature = "python", pyclass(get_all, set_all))]
#[cfg_attr(feature = "node", napi(object))]
#[cfg_attr(not(feature = "node"), derive(Clone))]
#[derive(Debug, Default, Serialize, Deserialize)]
pub struct UpdateWebhookParams {
    /// New human-readable name.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    /// New notification email.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub notification_email: Option<String>,
    /// New destination configuration.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub destination_attributes: Option<WebhookDestinationAttributes>,
}

#[cfg(feature = "python")]
#[gen_stub_pymethods]
#[pymethods]
impl UpdateWebhookParams {
    #[new]
    #[pyo3(signature = (name=None, notification_email=None, destination_attributes=None))]
    pub fn new(
        name: Option<String>,
        notification_email: Option<String>,
        destination_attributes: Option<WebhookDestinationAttributes>,
    ) -> Self {
        Self {
            name,
            notification_email,
            destination_attributes,
        }
    }
}

/// Parameters for `activate_webhook`.
#[cfg_attr(feature = "node", napi(object))]
#[cfg_attr(not(feature = "node"), derive(Clone))]
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ActivateWebhookParams {
    /// Position to begin (or resume) delivery from.
    pub start_from: WebhookStartFrom,
}

/// Parameters for `create_webhook_from_template`.
#[cfg_attr(feature = "rust", derive(Builder))]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CreateWebhookFromTemplateParams {
    /// Human-readable label for the webhook.
    pub name: String,
    /// Blockchain network to watch (e.g. `ethereum-mainnet`).
    pub network: String,
    /// Optional email that receives alerts if the webhook terminates.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub notification_email: Option<String>,
    /// Destination configuration for delivered payloads.
    pub destination_attributes: WebhookDestinationAttributes,
    /// Filter template identifier and its arguments.
    // Flattening the enum's tag/content produces { templateId, templateArgs }.
    #[serde(flatten)]
    pub template_args: TemplateArgs,
}

/// Parameters for `update_webhook_template`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UpdateWebhookTemplateParams {
    /// New human-readable name.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    /// New notification email.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub notification_email: Option<String>,
    /// New destination configuration.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub destination_attributes: Option<WebhookDestinationAttributes>,
    /// New template identifier and arguments.
    // Flattening the enum's tag/content produces { templateId, templateArgs }.
    #[serde(flatten)]
    pub template_args: TemplateArgs,
}

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

/// A webhook's full configuration and current state.
#[cfg_attr(feature = "python", gen_stub_pyclass)]
#[cfg_attr(feature = "python", pyclass(get_all, set_all))]
#[cfg_attr(feature = "node", napi(object))]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Webhook {
    /// Unique webhook identifier.
    pub id: String,
    /// Human-readable webhook name.
    pub name: String,
    /// Current operational state (e.g. `active`, `paused`).
    pub status: String,
    /// Blockchain network the webhook is watching.
    pub network: String,
    /// Timestamp when the webhook was created.
    pub created_at: String,
    /// Timestamp of the most recent modification.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub updated_at: Option<String>,
    /// Template identifier used to create the webhook, if any.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub template_id: Option<String>,
    /// Email address notified of webhook terminations or failures.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub notification_email: Option<String>,
    /// Destination-specific configuration as a JSON string.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "deserialize_as_optional_json_string"
    )]
    pub destination_attributes: Option<String>,
}

/// Pagination metadata returned alongside a paginated webhooks list.
#[cfg_attr(feature = "python", gen_stub_pyclass)]
#[cfg_attr(feature = "python", pyclass(get_all, set_all))]
#[cfg_attr(feature = "node", napi(object))]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WebhookPageInfo {
    /// Page size used for this response.
    pub limit: i64,
    /// Starting index of this page within the full result set.
    pub offset: i64,
    /// Total number of webhooks matching the query across all pages.
    pub total: i64,
}

/// Response from `list_webhooks`.
#[cfg_attr(feature = "python", gen_stub_pyclass)]
#[cfg_attr(feature = "python", pyclass(get_all, set_all))]
#[cfg_attr(feature = "node", napi(object))]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ListWebhooksResponse {
    /// Webhooks on the current page.
    pub data: Vec<Webhook>,
    /// Pagination metadata for the response.
    #[serde(rename = "pageInfo")]
    pub page_info: WebhookPageInfo,
}

/// Response from `get_enabled_count` for webhooks.
#[cfg_attr(feature = "python", gen_stub_pyclass)]
#[cfg_attr(feature = "python", pyclass(get_all, set_all))]
#[cfg_attr(feature = "node", napi(object))]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WebhookEnabledCountResponse {
    /// Total count of enabled webhooks on the account.
    pub total: i64,
}

#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod template_args_tests {
    use super::*;

    #[test]
    fn evm_wallet_filter_roundtrip() {
        let args =
            TemplateArgs::EvmWalletFilter(EvmWalletFilterInput::Inline(EvmWalletFilterTemplate {
                wallets: vec!["0xabc".to_string()],
            }));
        let json = serde_json::to_string(&args).unwrap();
        assert!(json.contains(r#""templateId":"evmWalletFilter""#));
        assert!(json.contains(r#""wallets":["0xabc"]"#));
        let parsed: TemplateArgs = serde_json::from_str(&json).unwrap();
        assert!(matches!(
            parsed,
            TemplateArgs::EvmWalletFilter(EvmWalletFilterInput::Inline(_))
        ));
        assert!(matches!(parsed.tag(), WebhookTemplateId::EvmWalletFilter));
    }

    #[test]
    fn evm_wallet_filter_by_list_roundtrip() {
        let args = TemplateArgs::EvmWalletFilter(EvmWalletFilterInput::ByList(
            EvmWalletFilterByListTemplate {
                wallets_list_name: "my_list".to_string(),
            },
        ));
        let json = serde_json::to_string(&args).unwrap();
        assert!(json.contains(r#""templateId":"evmWalletFilter""#));
        assert!(json.contains(r#""walletsListName":"my_list""#));
        assert!(!json.contains(r#""wallets":"#));
        let parsed: TemplateArgs = serde_json::from_str(&json).unwrap();
        assert!(matches!(
            parsed,
            TemplateArgs::EvmWalletFilter(EvmWalletFilterInput::ByList(_))
        ));
    }

    #[test]
    fn evm_contract_events_roundtrip() {
        let args = TemplateArgs::EvmContractEvents(EvmContractEventsInput::Inline(
            EvmContractEventsTemplate {
                contracts: vec!["0xdef".to_string()],
                event_hashes: vec!["0x1234".to_string()],
            },
        ));
        let json = serde_json::to_string(&args).unwrap();
        assert!(json.contains(r#""templateId":"evmContractEvents""#));
        // API expects camelCase `eventHashes` — snake_case is silently rejected with a 500.
        assert!(json.contains(r#""eventHashes":["0x1234"]"#));
        assert!(!json.contains("event_hashes"));
        let parsed: TemplateArgs = serde_json::from_str(&json).unwrap();
        assert!(matches!(
            parsed,
            TemplateArgs::EvmContractEvents(EvmContractEventsInput::Inline(_))
        ));
    }

    #[test]
    fn evm_contract_events_by_list_roundtrip() {
        // The ByList variant lets event_hashes_list_name be omitted entirely.
        let args = TemplateArgs::EvmContractEvents(EvmContractEventsInput::ByList(
            EvmContractEventsByListTemplate {
                contracts_list_name: "my_contracts".to_string(),
                event_hashes_list_name: None,
            },
        ));
        let json = serde_json::to_string(&args).unwrap();
        assert!(json.contains(r#""contractsListName":"my_contracts""#));
        assert!(!json.contains("eventHashesListName"));
        let parsed: TemplateArgs = serde_json::from_str(&json).unwrap();
        assert!(matches!(
            parsed,
            TemplateArgs::EvmContractEvents(EvmContractEventsInput::ByList(_))
        ));
    }

    #[test]
    fn evm_abi_filter_roundtrip() {
        let args = TemplateArgs::EvmAbiFilter(EvmAbiFilterInput::Inline(EvmAbiFilterTemplate {
            abi: "[]".to_string(),
            contracts: vec!["0xdef".to_string()],
        }));
        let json = serde_json::to_string(&args).unwrap();
        assert!(json.contains(r#""templateId":"evmAbiFilter""#));
        let parsed: TemplateArgs = serde_json::from_str(&json).unwrap();
        assert!(matches!(parsed, TemplateArgs::EvmAbiFilter(_)));
    }

    #[test]
    fn evm_abi_filter_by_list_roundtrip() {
        // The ByList variant uses `abiJson` (distinct from inline's `abi`) and
        // an optional `contractsListName`.
        let args =
            TemplateArgs::EvmAbiFilter(EvmAbiFilterInput::ByList(EvmAbiFilterByListTemplate {
                abi_json: "[]".to_string(),
                contracts_list_name: Some("my_contracts".to_string()),
            }));
        let json = serde_json::to_string(&args).unwrap();
        assert!(json.contains(r#""abiJson":"[]""#));
        assert!(json.contains(r#""contractsListName":"my_contracts""#));
        assert!(!json.contains(r#""abi":"#));
        let parsed: TemplateArgs = serde_json::from_str(&json).unwrap();
        assert!(matches!(
            parsed,
            TemplateArgs::EvmAbiFilter(EvmAbiFilterInput::ByList(_))
        ));
    }

    #[test]
    fn solana_wallet_filter_roundtrip() {
        let args = TemplateArgs::SolanaWalletFilter(SolanaWalletFilterInput::Inline(
            SolanaWalletFilterTemplate {
                accounts: vec!["acc".to_string()],
            },
        ));
        let json = serde_json::to_string(&args).unwrap();
        assert!(json.contains(r#""templateId":"solanaWalletFilter""#));
        let parsed: TemplateArgs = serde_json::from_str(&json).unwrap();
        assert!(matches!(parsed, TemplateArgs::SolanaWalletFilter(_)));
    }

    #[test]
    fn solana_wallet_filter_by_list_roundtrip() {
        let args = TemplateArgs::SolanaWalletFilter(SolanaWalletFilterInput::ByList(
            SolanaWalletFilterByListTemplate {
                accounts_list_name: "my_accounts".to_string(),
            },
        ));
        let json = serde_json::to_string(&args).unwrap();
        assert!(json.contains(r#""accountsListName":"my_accounts""#));
        assert!(!json.contains(r#""accounts":"#));
    }

    #[test]
    fn bitcoin_wallet_filter_roundtrip() {
        let args = TemplateArgs::BitcoinWalletFilter(BitcoinWalletFilterInput::Inline(
            BitcoinWalletFilterTemplate {
                wallets: vec!["bc1".to_string()],
            },
        ));
        let json = serde_json::to_string(&args).unwrap();
        assert!(json.contains(r#""templateId":"bitcoinWalletFilter""#));
        let parsed: TemplateArgs = serde_json::from_str(&json).unwrap();
        assert!(matches!(parsed, TemplateArgs::BitcoinWalletFilter(_)));
    }

    #[test]
    fn bitcoin_wallet_filter_by_list_roundtrip() {
        let args = TemplateArgs::BitcoinWalletFilter(BitcoinWalletFilterInput::ByList(
            BitcoinWalletFilterByListTemplate {
                wallets_list_name: "my_btc_list".to_string(),
            },
        ));
        let json = serde_json::to_string(&args).unwrap();
        assert!(json.contains(r#""walletsListName":"my_btc_list""#));
    }

    #[test]
    fn xrpl_wallet_filter_roundtrip() {
        let args = TemplateArgs::XrplWalletFilter(XrplWalletFilterInput::Inline(
            XrplWalletFilterTemplate {
                wallets: vec!["r1".to_string()],
            },
        ));
        let json = serde_json::to_string(&args).unwrap();
        assert!(json.contains(r#""templateId":"xrplWalletFilter""#));
        let parsed: TemplateArgs = serde_json::from_str(&json).unwrap();
        assert!(matches!(parsed, TemplateArgs::XrplWalletFilter(_)));
    }

    #[test]
    fn xrpl_wallet_filter_by_list_roundtrip() {
        let args = TemplateArgs::XrplWalletFilter(XrplWalletFilterInput::ByList(
            XrplWalletFilterByListTemplate {
                wallets_list_name: "my_xrpl_list".to_string(),
            },
        ));
        let json = serde_json::to_string(&args).unwrap();
        assert!(json.contains(r#""walletsListName":"my_xrpl_list""#));
    }

    #[test]
    fn hyperliquid_wallet_events_filter_roundtrip() {
        let args = TemplateArgs::HyperliquidWalletEventsFilter(
            HyperliquidWalletEventsFilterInput::Inline(HyperliquidWalletEventsFilterTemplate {
                wallets: vec!["0xhl".to_string()],
            }),
        );
        let json = serde_json::to_string(&args).unwrap();
        assert!(json.contains(r#""templateId":"hyperliquidWalletEventsFilter""#));
        let parsed: TemplateArgs = serde_json::from_str(&json).unwrap();
        assert!(matches!(
            parsed,
            TemplateArgs::HyperliquidWalletEventsFilter(_)
        ));
    }

    #[test]
    fn hyperliquid_wallet_events_filter_by_list_roundtrip() {
        let args = TemplateArgs::HyperliquidWalletEventsFilter(
            HyperliquidWalletEventsFilterInput::ByList(
                HyperliquidWalletEventsFilterByListTemplate {
                    wallets_list_name: "my_hl_list".to_string(),
                },
            ),
        );
        let json = serde_json::to_string(&args).unwrap();
        assert!(json.contains(r#""walletsListName":"my_hl_list""#));
    }

    #[test]
    fn stellar_wallet_transactions_filter_roundtrip() {
        let args = TemplateArgs::StellarWalletTransactionsSourceAccountFilter(
            StellarWalletTransactionsFilterInput::Inline(StellarWalletTransactionsFilterTemplate {
                wallets: vec!["G...".to_string()],
            }),
        );
        let json = serde_json::to_string(&args).unwrap();
        assert!(json.contains(r#""templateId":"stellarWalletTransactionsSourceAccountFilter""#));
        let parsed: TemplateArgs = serde_json::from_str(&json).unwrap();
        assert!(matches!(
            parsed,
            TemplateArgs::StellarWalletTransactionsSourceAccountFilter(_)
        ));
    }

    #[test]
    fn stellar_wallet_transactions_filter_by_list_roundtrip() {
        let args = TemplateArgs::StellarWalletTransactionsSourceAccountFilter(
            StellarWalletTransactionsFilterInput::ByList(
                StellarWalletTransactionsFilterByListTemplate {
                    wallets_list_name: "my_stellar_list".to_string(),
                },
            ),
        );
        let json = serde_json::to_string(&args).unwrap();
        assert!(json.contains(r#""walletsListName":"my_stellar_list""#));
    }

    #[test]
    fn create_params_flattens_template_args() {
        let params = CreateWebhookFromTemplateParams {
            name: "n".to_string(),
            network: "ethereum-mainnet".to_string(),
            notification_email: None,
            destination_attributes: WebhookDestinationAttributes {
                url: "https://x".to_string(),
                security_token: None,
                compression: "none".to_string(),
            },
            template_args: TemplateArgs::EvmWalletFilter(EvmWalletFilterInput::Inline(
                EvmWalletFilterTemplate {
                    wallets: vec!["0xabc".to_string()],
                },
            )),
        };
        let json = serde_json::to_value(&params).unwrap();
        let obj = json.as_object().unwrap();
        assert_eq!(
            obj.get("templateId").and_then(|v| v.as_str()),
            Some("evmWalletFilter")
        );
        assert!(obj.get("templateArgs").unwrap().is_object());
        assert_eq!(obj["templateArgs"]["wallets"][0].as_str(), Some("0xabc"));
    }
}