sails-rs 1.0.1

Main abstractions for the Sails framework
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
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
use crate::meta::SailsMessageHeader;
use crate::prelude::*;
use core::{
    any::TypeId,
    error::Error,
    marker::PhantomData,
    pin::Pin,
    task::{Context, Poll},
};
use futures::Stream;
pub use sails_idl_meta::{Identifiable, InterfaceId, MethodMeta};

#[cfg(all(feature = "gtest", not(target_arch = "wasm32")))]
mod gtest_env;
#[cfg(all(feature = "gtest", not(target_arch = "wasm32")))]
pub use gtest_env::*;

#[cfg(all(feature = "gclient", not(target_arch = "wasm32")))]
mod gclient_env;
#[cfg(all(feature = "gclient", not(target_arch = "wasm32")))]
pub use gclient_env::{GclientEnv, GclientError, GclientParams};

mod gstd_env;
pub use gstd_env::{GstdEnv, GstdParams};

pub(crate) const PENDING_CALL_INVALID_STATE: &str =
    "PendingCall polled after completion or invalid state";
pub(crate) const PENDING_CTOR_INVALID_STATE: &str =
    "PendingCtor polled after completion or invalid state";

// --- Route header typestate ---

/// Alias for v1 service route strings (OLD IDL protocol).
pub type Route = &'static str;

/// Typestate marker for route-header encoding.
pub trait RouteHeader: Clone + core::fmt::Debug {}

/// v2 (NEW IDL) binary-header route: numeric route index (default).
#[derive(Debug, Clone, Copy, Default)]
pub struct RouteIdx(pub u8);
impl RouteHeader for RouteIdx {}

/// v1 (OLD IDL) SCALE-string route: carries the service route string at runtime.
/// Ctor services use `RouteName("")` (no service prefix).
#[derive(Debug, Clone, Copy, Default)]
pub struct RouteName(pub Route);
impl RouteHeader for RouteName {}

// --- GearEnv and related ---

pub trait GearEnv: Clone {
    type Params: Default;
    type Error: Error;
    type MessageState;

    fn deploy<P: Program>(&self, code_id: CodeId, salt: Vec<u8>) -> Deployment<P, Self> {
        Deployment::new(self.clone(), code_id, salt)
    }
}

pub trait Program: Sized {
    fn deploy(code_id: CodeId, salt: Vec<u8>) -> Deployment<Self, GstdEnv> {
        Deployment::new(GstdEnv, code_id, salt)
    }

    fn client(program_id: ActorId) -> Actor<Self, GstdEnv> {
        Actor::new(GstdEnv, program_id)
    }
}

#[derive(Debug, Clone)]
pub struct Deployment<A, E: GearEnv = GstdEnv> {
    env: E,
    code_id: CodeId,
    salt: Vec<u8>,
    _phantom: PhantomData<A>,
}

impl<A, E: GearEnv> Deployment<A, E> {
    pub fn new(env: E, code_id: CodeId, salt: Vec<u8>) -> Self {
        Deployment {
            env,
            code_id,
            salt,
            _phantom: PhantomData,
        }
    }

    pub fn with_env<N: GearEnv>(self, env: &N) -> Deployment<A, N> {
        let Self {
            env: _,
            code_id,
            salt,
            _phantom: _,
        } = self;
        Deployment {
            env: env.clone(),
            code_id,
            salt,
            _phantom: PhantomData,
        }
    }

    /// v2 (NEW IDL, default) ctor.
    pub fn pending_ctor<T>(self, args: T::Params) -> PendingCtor<A, T, E>
    where
        T: ServiceCall<Route = RouteIdx>,
    {
        PendingCtor::new(self.env, self.code_id, self.salt, RouteIdx(0), args)
    }

    /// v1 (OLD IDL) ctor. Ctors have no service prefix — uses `RouteName("")`.
    pub fn pending_ctor_v1<T>(self, args: T::Params) -> PendingCtor<A, T, E>
    where
        T: ServiceCall<Route = RouteName>,
    {
        PendingCtor::new(self.env, self.code_id, self.salt, RouteName(""), args)
    }
}

#[derive(Debug, Clone)]
pub struct Actor<A, E: GearEnv = GstdEnv> {
    env: E,
    id: ActorId,
    _phantom: PhantomData<A>,
}

impl<A, E: GearEnv> Actor<A, E> {
    pub fn new(env: E, id: ActorId) -> Self {
        Actor {
            env,
            id,
            _phantom: PhantomData,
        }
    }

    pub fn id(&self) -> ActorId {
        self.id
    }

    pub fn with_env<N: GearEnv>(self, env: &N) -> Actor<A, N> {
        let Self {
            env: _,
            id,
            _phantom: _,
        } = self;
        Actor {
            env: env.clone(),
            id,
            _phantom: PhantomData,
        }
    }

    pub fn with_actor_id(mut self, actor_id: ActorId) -> Self {
        self.id = actor_id;
        self
    }

    /// v2 (NEW IDL, default): service identified by numeric route index.
    pub fn service<S>(&self, route_idx: u8) -> Service<S, E> {
        Service::new(self.env.clone(), self.id, RouteIdx(route_idx))
    }

    /// v1 (OLD IDL): service identified by its IDL name (empty string for anonymous).
    pub fn service_v1<S>(&self, name: Route) -> Service<S, E, RouteName> {
        Service::new(self.env.clone(), self.id, RouteName(name))
    }
}

#[derive(Debug, Clone)]
pub struct Service<S, E: GearEnv = GstdEnv, R: RouteHeader = RouteIdx> {
    env: E,
    actor_id: ActorId,
    route: R,
    _phantom: PhantomData<S>,
}

impl<S, E: GearEnv, R: RouteHeader> Service<S, E, R> {
    pub fn new(env: E, actor_id: ActorId, route: R) -> Self {
        Service {
            env,
            actor_id,
            route,
            _phantom: PhantomData,
        }
    }

    pub fn actor_id(&self) -> ActorId {
        self.actor_id
    }

    pub fn with_actor_id(mut self, actor_id: ActorId) -> Self {
        self.actor_id = actor_id;
        self
    }

    pub fn pending_call<T: ServiceCall<Route = R>>(&self, args: T::Params) -> PendingCall<T, E> {
        PendingCall::new(self.env.clone(), self.actor_id, self.route.clone(), args)
    }

    pub fn base_service<B>(&self) -> Service<B, E, R> {
        Service::new(self.env.clone(), self.actor_id, self.route.clone())
    }

    #[cfg(not(target_arch = "wasm32"))]
    pub fn decode_event<Ev: Event<R>>(
        &self,
        payload: impl AsRef<[u8]>,
    ) -> Result<Ev, parity_scale_codec::Error> {
        Ev::decode_event(&self.route, payload)
    }

    #[cfg(not(target_arch = "wasm32"))]
    pub async fn listen(
        &self,
    ) -> Result<impl Stream<Item = (ActorId, S::Event)> + Unpin + use<S, E, R>, <E as GearEnv>::Error>
    where
        S: ServiceWithEvents<R>,
        E: Listener<Error = <E as GearEnv>::Error>,
    {
        let self_id = self.actor_id;
        let route = self.route.clone();
        self.env
            .listen(move |(actor_id, payload)| {
                if actor_id != self_id {
                    return None;
                }
                S::Event::decode_event(&route, payload)
                    .ok()
                    .map(|e| (actor_id, e))
            })
            .await
    }
}

// v2-specific id accessors only on RouteIdx
impl<S, E: GearEnv> Service<S, E, RouteIdx> {
    pub fn interface_id(&self) -> InterfaceId
    where
        S: Identifiable,
    {
        S::INTERFACE_ID
    }

    pub fn route_idx(&self) -> u8 {
        self.route.0
    }
}

#[cfg(not(target_arch = "wasm32"))]
pub trait ServiceWithEvents<R: RouteHeader = RouteIdx> {
    type Event: Event<R>;
}

pin_project_lite::pin_project! {
    pub struct PendingCall<T: ServiceCall, E: GearEnv = GstdEnv> {
        env: E,
        destination: ActorId,
        route: T::Route,
        params: Option<E::Params>,
        args: Option<T::Params>,
        #[pin]
        state: Option<E::MessageState>
    }
}

impl<T: ServiceCall, E: GearEnv> PendingCall<T, E> {
    pub fn new(env: E, destination: ActorId, route: T::Route, args: T::Params) -> Self {
        PendingCall {
            env,
            destination,
            route,
            params: None,
            args: Some(args),
            state: None,
        }
    }

    pub fn with_destination(mut self, actor_id: ActorId) -> Self {
        self.destination = actor_id;
        self
    }

    pub fn with_params(mut self, f: impl FnOnce(E::Params) -> E::Params) -> Self {
        self.params = Some(f(self.params.unwrap_or_default()));
        self
    }

    pub fn encode_call(mut self) -> Vec<u8> {
        let (payload, _) = self.take_encoded_args_and_params();
        payload
    }

    #[inline]
    pub(crate) fn take_encoded_args_and_params(&mut self) -> (Vec<u8>, E::Params) {
        let args = self
            .args
            .take()
            .unwrap_or_else(|| panic!("{PENDING_CALL_INVALID_STATE}"));
        let payload = T::encode_call(&self.route, &args);
        let params = self.params.take().unwrap_or_default();
        (payload, params)
    }
}

pub trait PendingCtorOutput<A, E: GearEnv> {
    type Output;

    fn map_result(self, env: E, id: ActorId) -> Self::Output;

    fn actor(output: Self::Output) -> Actor<A, E>;
}

impl<A, E: GearEnv> PendingCtorOutput<A, E> for () {
    type Output = Actor<A, E>;

    fn map_result(self, env: E, id: ActorId) -> Self::Output {
        Actor::new(env, id)
    }

    fn actor(output: Self::Output) -> Actor<A, E> {
        output
    }
}

impl<A, E: GearEnv, Err: core::fmt::Debug> PendingCtorOutput<A, E> for Result<(), Err> {
    type Output = Result<Actor<A, E>, Err>;

    fn map_result(self, env: E, id: ActorId) -> Self::Output {
        self.map(|_| Actor::new(env, id))
    }

    fn actor(output: Self::Output) -> Actor<A, E> {
        output.expect("PendingCtor output is not Ok")
    }
}

pin_project_lite::pin_project! {
    pub struct PendingCtor<A, T: ServiceCall, E: GearEnv = GstdEnv> {
        env: E,
        code_id: CodeId,
        route: T::Route,
        params: Option<E::Params>,
        salt: Option<Vec<u8>>,
        args: Option<T::Params>,
        _actor: PhantomData<A>,
        #[pin]
        state: Option<E::MessageState>,
        program_id: Option<ActorId>,
    }
}

impl<A, T: ServiceCall, E: GearEnv> PendingCtor<A, T, E> {
    pub fn new(env: E, code_id: CodeId, salt: Vec<u8>, route: T::Route, args: T::Params) -> Self {
        PendingCtor {
            env,
            code_id,
            route,
            params: None,
            salt: Some(salt),
            args: Some(args),
            state: None,
            program_id: None,
            _actor: PhantomData,
        }
    }

    pub fn with_params(mut self, f: impl FnOnce(E::Params) -> E::Params) -> Self {
        self.params = Some(f(self.params.unwrap_or_default()));
        self
    }
}

/// Unified service-call codec parameterized by route header.
///
pub trait ServiceCall {
    type Route: RouteHeader;
    type Params;
    type Reply;
    /// Application-level error type (IDL `throws`). Always `()` for v1.
    type Throws;
    type Output;

    fn encode_call(route: &Self::Route, value: &Self::Params) -> Vec<u8>;

    fn decode_reply(
        route: &Self::Route,
        payload: impl AsRef<[u8]>,
    ) -> Result<Self::Output, parity_scale_codec::Error>;

    fn decode_error(
        route: &Self::Route,
        payload: impl AsRef<[u8]>,
    ) -> Result<Self::Output, parity_scale_codec::Error>;
}

// --- Standalone helpers (previously on the ServiceCall trait) ---

/// v2-specific: decode a reply payload that has a SailsMessageHeader prefix.
/// Used internally by `io_struct_impl!`.
pub fn decode_with_header<T, M>(
    route_idx: u8,
    payload: impl AsRef<[u8]>,
) -> Result<T, parity_scale_codec::Error>
where
    T: Decode + 'static,
    M: MethodMeta + Identifiable,
{
    let mut value = payload.as_ref();
    if is_empty_tuple::<T>() {
        return Decode::decode(&mut value);
    }
    let header = SailsMessageHeader::decode(&mut value)?;
    if header.interface_id() != M::INTERFACE_ID {
        return Err("Invalid reply interface_id".into());
    }
    if header.route_id() != route_idx {
        return Err("Invalid reply route_idx".into());
    }
    if header.entry_id() != M::ENTRY_ID {
        return Err("Invalid reply entry_id".into());
    }
    Decode::decode(&mut value)
}

/// Returns true if `T` is the unit type `()`.
pub fn is_empty_tuple<T>() -> bool
where
    T: 'static,
{
    TypeId::of::<T>() == TypeId::of::<()>()
}

/// Env error type that [`decode_reply_or_throw`] can inspect to recover an
/// application-level `throws` value from a userspace-panic reply.
pub trait ReplyError: Sized {
    /// Wrap a SCALE decode failure of a reply payload.
    fn from_codec_error(err: parity_scale_codec::Error) -> Self;

    /// If this error is a userspace panic carrying a reply payload, return that payload.
    fn userspace_panic_payload(&self) -> Option<&[u8]>;
}

/// Decodes a raw reply against `route`:
/// - `Ok(payload)` is decoded via [`ServiceCall::decode_reply`];
/// - a userspace-panic error is decoded via [`ServiceCall::decode_error`] to recover a
///   `throws` value, falling back to the original error when that fails;
/// - any other error is propagated unchanged.
pub fn decode_reply_or_throw<T: ServiceCall, E: ReplyError>(
    route: &T::Route,
    reply: Result<Vec<u8>, E>,
) -> Result<T::Output, E> {
    match reply {
        Ok(payload) => T::decode_reply(route, payload).map_err(E::from_codec_error),
        Err(err) => {
            if let Some(payload) = err.userspace_panic_payload()
                && let Ok(reply) = T::decode_error(route, payload)
            {
                return Ok(reply);
            }
            Err(err)
        }
    }
}

/// v2-specific: encode a call using a stack buffer (zero-copy, requires `gcore`).
/// Used in wasm32 on-chain dispatch code via the `io_struct_impl!` inherent methods.
pub fn encode_call_optimized<T, R>(
    route_idx: u8,
    value: &T::Params,
    f: impl FnOnce(&[u8]) -> R,
) -> R
where
    T: ServiceCall<Route = RouteIdx> + MethodMeta + Identifiable,
    T::Params: Encode,
{
    encode_call_optimized_with_id::<T, R>(T::INTERFACE_ID, T::ENTRY_ID, route_idx, value, f)
}

pub fn encode_call_optimized_with_id<T, R>(
    interface_id: InterfaceId,
    entry_id: u16,
    route_idx: u8,
    value: &T::Params,
    f: impl FnOnce(&[u8]) -> R,
) -> R
where
    T: ServiceCall<Route = RouteIdx>,
    T::Params: Encode,
{
    let header = SailsMessageHeader::new(
        crate::meta::Version::v1(),
        crate::meta::HeaderLength::new(crate::meta::MINIMAL_HLEN).unwrap(),
        interface_id,
        route_idx,
        entry_id,
    );
    let size = (crate::meta::MINIMAL_HLEN as usize) + Encode::encoded_size(value);
    gcore::stack_buffer::with_byte_buffer(size, |buffer| {
        let mut buffer_writer = crate::utils::MaybeUninitBufferWriter::new(buffer);
        header.encode_to(&mut buffer_writer);
        Encode::encode_to(value, &mut buffer_writer);
        buffer_writer.with_buffer(f)
    })
}

#[macro_export]
macro_rules! params_struct_impl {
    (
        $env:ident,
        $name:ident { $( $(#[$attr:meta])* $vis:vis $field:ident: $ty:ty ),* $(,)?  }
    ) => {
        #[derive(Debug, Default)]
        pub struct $name {
            $(
                $(#[$attr])* $vis $field : Option< $ty >,
            )*
        }

        impl $name {
            $(
                paste::paste! {
                    $(#[$attr])*
                    pub fn [<with_ $field>](mut self, $field: $ty) -> Self {
                        self.$field = Some($field);
                        self
                    }
                }
            )*
        }

        impl<A, T: $crate::client::ServiceCall> $crate::client::PendingCtor<A, T, $env> {
            $(
                paste::paste! {
                    $(#[$attr])*
                    pub fn [<with_ $field>](self, $field: $ty) -> Self {
                        self.with_params(|params| params.[<with_ $field>]($field))
                    }
                }
            )*
        }

        impl<T: $crate::client::ServiceCall> $crate::client::PendingCall<T, $env> {
            $(
                paste::paste! {
                    $(#[$attr])*
                    pub fn [<with_ $field>](self, $field: $ty) -> Self {
                        self.with_params(|params| params.[<with_ $field>]($field))
                    }
                }
            )*
        }
    };
}

#[macro_export]
macro_rules! params_for_pending_impl {
    (
        $env:ident,
        $name:ident { $( $(#[$attr:meta])* $vis:vis $field:ident: $ty:ty ),* $(,)?  }
    ) => {
        impl $name {
            $(
                paste::paste! {
                    $(#[$attr])*
                    pub fn [<with_ $field>](mut self, $field: $ty) -> Self {
                        self.$field = Some($field);
                        self
                    }
                }
            )*
        }

        impl<A, T: $crate::client::ServiceCall> $crate::client::PendingCtor<A, T, $env> {
            $(
                paste::paste! {
                    $(#[$attr])*
                    pub fn [<with_ $field>](self, $field: $ty) -> Self {
                        self.with_params(|params| params.[<with_ $field>]($field))
                    }
                }
            )*
        }

        impl<T: $crate::client::ServiceCall> $crate::client::PendingCall<T, $env> {
            $(
                paste::paste! {
                    $(#[$attr])*
                    pub fn [<with_ $field>](self, $field: $ty) -> Self {
                        self.with_params(|params| params.[<with_ $field>]($field))
                    }
                }
            )*
        }
    };
}

#[macro_export]
macro_rules! io_struct_impl {
    // 3-arg form: service method with entry_id + interface_id (no throws)
    (
        $name:ident ( $( $param:ident : $ty:ty ),* ) -> $reply:ty, $entry_id:expr, $interface_id:expr
    ) => {
        $crate::io_struct_impl!(@impl_base $name ( $( $param : $ty ),* ) -> $reply, $entry_id, $interface_id);

        impl $crate::client::ServiceCall for $name {
            type Route = $crate::client::RouteIdx;
            type Params = ( $( $ty, )* );
            type Reply = $reply;
            type Throws = ();
            type Output = $reply;

            fn encode_call(route: &$crate::client::RouteIdx, value: &Self::Params) -> Vec<u8> {
                let header = $crate::meta::SailsMessageHeader::new(
                    $crate::meta::Version::v1(),
                    $crate::meta::HeaderLength::new($crate::meta::MINIMAL_HLEN).unwrap(),
                    <$name as $crate::client::Identifiable>::INTERFACE_ID,
                    route.0,
                    <$name as $crate::client::MethodMeta>::ENTRY_ID,
                );
                let mut result = header.to_bytes();
                $crate::prelude::Encode::encode_to(value, &mut result);
                result
            }

            fn decode_reply(
                route: &$crate::client::RouteIdx,
                payload: impl AsRef<[u8]>,
            ) -> Result<Self::Output, $crate::scale_codec::Error> {
                $crate::client::decode_with_header::<Self::Reply, $name>(route.0, payload)
            }

            fn decode_error(
                _route: &$crate::client::RouteIdx,
                _payload: impl AsRef<[u8]>,
            ) -> Result<Self::Output, $crate::scale_codec::Error> {
                Err("Throws type is `()`".into())
            }
        }
    };
    // 3-arg form with throws
    (
        $name:ident ( $( $param:ident : $ty:ty ),* ) -> $reply:ty | $throws:ty, $entry_id:expr, $interface_id:expr
    ) => {
        $crate::io_struct_impl!(@impl_base $name ( $( $param : $ty ),* ) -> $reply, $entry_id, $interface_id);

        impl $crate::client::ServiceCall for $name {
            type Route = $crate::client::RouteIdx;
            type Params = ( $( $ty, )* );
            type Reply = $reply;
            type Throws = $throws;
            type Output = Result<$reply, $throws>;

            fn encode_call(route: &$crate::client::RouteIdx, value: &Self::Params) -> Vec<u8> {
                let header = $crate::meta::SailsMessageHeader::new(
                    $crate::meta::Version::v1(),
                    $crate::meta::HeaderLength::new($crate::meta::MINIMAL_HLEN).unwrap(),
                    <$name as $crate::client::Identifiable>::INTERFACE_ID,
                    route.0,
                    <$name as $crate::client::MethodMeta>::ENTRY_ID,
                );
                let mut result = header.to_bytes();
                $crate::prelude::Encode::encode_to(value, &mut result);
                result
            }

            fn decode_reply(
                route: &$crate::client::RouteIdx,
                payload: impl AsRef<[u8]>,
            ) -> Result<Self::Output, $crate::scale_codec::Error> {
                Ok(Ok($crate::client::decode_with_header::<Self::Reply, $name>(route.0, payload)?))
            }

            fn decode_error(
                route: &$crate::client::RouteIdx,
                payload: impl AsRef<[u8]>,
            ) -> Result<Self::Output, $crate::scale_codec::Error> {
                Ok(Err($crate::client::decode_with_header::<Self::Throws, $name>(route.0, payload)?))
            }
        }
    };
    // 2-arg form: ctor method (InterfaceId::zero)
    (
        $name:ident ( $( $param:ident : $ty:ty ),* ) -> $reply:ty $( | $throws:ty )?, $entry_id:expr
    ) => {
        $crate::io_struct_impl!($name ( $( $param : $ty ),* ) -> $reply $( | $throws )?, $entry_id, $crate::meta::InterfaceId::zero());
    };
    // @impl_base: struct + Identifiable + MethodMeta + convenience inherent methods
    (
        @impl_base $name:ident ( $( $param:ident : $ty:ty ),* ) -> $reply:ty, $entry_id:expr, $interface_id:expr
    ) => {
        pub struct $name(());
        impl $name {
            /// Encodes the full call with the correct Sails header.
            pub fn encode_call(route_idx: u8, $( $param: $ty, )* ) -> Vec<u8> {
                <$name as $crate::client::ServiceCall>::encode_call(
                    &$crate::client::RouteIdx(route_idx), &( $( $param, )* )
                )
            }
            /// Decodes the reply checking against the correct Sails header.
            pub fn decode_reply(route_idx: u8, payload: impl AsRef<[u8]>) -> Result<$reply, $crate::scale_codec::Error> {
                $crate::client::decode_with_header::<$reply, $name>(route_idx, payload)
            }
        }
        impl $crate::client::Identifiable for $name {
            const INTERFACE_ID: $crate::meta::InterfaceId = $interface_id;
        }
        impl $crate::client::MethodMeta for $name {
            const ENTRY_ID: u16 = $entry_id;
        }
    };
}

/// v1 (OLD IDL, SCALE-string encoded) service/ctor IO struct.
///
/// `ServiceCall<RouteName>` uses the route string from the `RouteName` instance
/// passed at call time (set by `Actor::service_v1(name)` / `pending_ctor_v1`).
///
/// v1 has NO `throws` concept — `Throws` is always `()` and `Output = Reply`.
///
/// Encoding: `SCALE(route.0) + SCALE(stringify!($name)) + SCALE(params)`
/// If `route.0` is empty (ctor / anonymous service), the service prefix is omitted.
#[macro_export]
macro_rules! io_struct_impl_v1 {
    (
        $name:ident ( $( $param:ident : $ty:ty ),* ) -> $reply:ty
    ) => {
        pub struct $name(());

        impl $name {
            pub fn encode_call(route: $crate::client::Route, $( $param: $ty, )* ) -> Vec<u8> {
                <$name as $crate::client::ServiceCall>::encode_call(
                    &$crate::client::RouteName(route), &( $( $param, )* )
                )
            }

            pub fn decode_reply(route: $crate::client::Route, payload: impl AsRef<[u8]>) -> Result<$reply, $crate::scale_codec::Error> {
                <$name as $crate::client::ServiceCall>::decode_reply(
                    &$crate::client::RouteName(route),
                    payload,
                )
            }
        }

        impl $crate::client::ServiceCall for $name {
            type Route = $crate::client::RouteName;
            type Params = ( $( $ty, )* );
            type Reply = $reply;
            // v1 has no `throws` concept — always unit, Output == Reply.
            type Throws = ();
            type Output = $reply;

            fn encode_call(
                route: &$crate::client::RouteName,
                value: &Self::Params,
            ) -> Vec<u8> {
                use $crate::prelude::Encode as _;
                let mut result = Vec::new();
                if !route.0.is_empty() {
                    route.0.encode_to(&mut result);
                }
                stringify!($name).encode_to(&mut result);
                value.encode_to(&mut result);
                result
            }

            fn decode_reply(
                route: &$crate::client::RouteName,
                payload: impl AsRef<[u8]>,
            ) -> Result<Self::Output, $crate::scale_codec::Error> {
                use $crate::prelude::Decode as _;
                let mut value = payload.as_ref();
                if $crate::client::is_empty_tuple::<$reply>() {
                    return $crate::prelude::Decode::decode(&mut value);
                }
                if !route.0.is_empty() {
                    let svc = String::decode(&mut value)?;
                    if svc != route.0 {
                        return Err("Invalid reply service route".into());
                    }
                }
                let method = String::decode(&mut value)?;
                if method != stringify!($name) {
                    return Err("Invalid reply method route".into());
                }
                $crate::prelude::Decode::decode(&mut value)
            }

            fn decode_error(
                _route: &$crate::client::RouteName,
                _payload: impl AsRef<[u8]>,
            ) -> Result<Self::Output, $crate::scale_codec::Error> {
                Err("Throws type is `()` for v1".into())
            }
        }
    };
}

#[allow(unused_macros)]
macro_rules! str_scale_encode {
    ($s:ident) => {{
        const S: &str = stringify!($s);
        assert!(S.len() <= 63, "Ident too long for encoding");
        const LEN: u8 = S.len() as u8;
        const BYTES: [u8; LEN as usize + 1] = {
            const fn to_array(s: &str) -> [u8; LEN as usize + 1] {
                let bytes = s.as_bytes();
                let mut out = [0u8; LEN as usize + 1];
                out[0] = LEN << 2;
                let mut i = 0;
                while i < LEN as usize {
                    out[i + 1] = bytes[i];
                    i += 1;
                }
                out
            }
            to_array(S)
        };
        BYTES.as_slice()
    }};
}

#[allow(async_fn_in_trait)]
pub trait Listener {
    type Error: Error;

    async fn listen<E, F>(
        &self,
        f: F,
    ) -> Result<impl Stream<Item = (ActorId, E)> + Unpin + use<Self, E, F>, Self::Error>
    where
        F: FnMut((ActorId, Vec<u8>)) -> Option<(ActorId, E)>;
}

#[cfg(not(target_arch = "wasm32"))]
struct EventInput<'a> {
    idx: u8,
    payload: &'a [u8],
    first: bool,
}

#[cfg(not(target_arch = "wasm32"))]
impl<'a> parity_scale_codec::Input for EventInput<'a> {
    fn remaining_len(&mut self) -> Result<Option<usize>, parity_scale_codec::Error> {
        Ok(Some(1 + self.payload.len()))
    }

    fn read(&mut self, into: &mut [u8]) -> Result<(), parity_scale_codec::Error> {
        if into.is_empty() {
            return Ok(());
        }
        let (head, tail) = into.split_at_mut(if self.first { 1 } else { 0 });
        if self.first {
            head[0] = self.idx;
            self.first = false;
        }
        if tail.is_empty() {
            return Ok(());
        }
        if tail.len() > self.payload.len() {
            return Err("Not enough data to fill buffer".into());
        }
        tail.copy_from_slice(&self.payload[..tail.len()]);
        self.payload = &self.payload[tail.len()..];
        Ok(())
    }

    fn read_byte(&mut self) -> Result<u8, parity_scale_codec::Error> {
        if self.first {
            self.first = false;
            Ok(self.idx)
        } else {
            let b = *self.payload.first().ok_or("Not enough data to read byte")?;
            self.payload = &self.payload[1..];
            Ok(b)
        }
    }
}

// --- Event traits ---

/// v1 (OLD IDL): compile-time list of event variant names.
/// Implemented by `client-gen-v1`-generated event enums.
#[cfg(not(target_arch = "wasm32"))]
pub trait EventNames {
    const EVENT_NAMES: &'static [Route];
}

/// v2-specific: decode an event payload using SailsMessageHeader.
/// Used by v2-generated `impl Event<RouteIdx>` blocks.
#[cfg(not(target_arch = "wasm32"))]
pub fn decode_event_v2<E>(
    route_idx: u8,
    payload: impl AsRef<[u8]>,
) -> Result<E, parity_scale_codec::Error>
where
    E: Decode + Identifiable,
{
    let mut payload = payload.as_ref();

    let header = SailsMessageHeader::decode(&mut payload)?;
    if header.interface_id() != E::INTERFACE_ID {
        return Err("Invalid event interface_id".into());
    }
    if header.route_id() != route_idx {
        return Err("Invalid event route_idx".into());
    }

    let entry_id = header.entry_id();
    if entry_id > 255 {
        return Err("Entry ID exceeds u8 limit for SCALE enum".into());
    }

    let variant_index = entry_id as u8;
    let mut input = EventInput {
        idx: variant_index,
        payload,
        first: true,
    };
    Decode::decode(&mut input)
}

/// v1-specific: decode an event payload encoded as `SCALE(variant_name) + SCALE(data)`.
#[cfg(not(target_arch = "wasm32"))]
pub fn decode_event_v1<E>(
    route: Route,
    payload: impl AsRef<[u8]>,
) -> Result<E, parity_scale_codec::Error>
where
    E: Decode + EventNames,
{
    let mut payload = payload.as_ref();
    let payload_route = String::decode(&mut payload)?;
    if payload_route != route {
        return Err("Invalid v1 event route".into());
    }
    let name = String::decode(&mut payload)?;
    let idx = <E as EventNames>::EVENT_NAMES
        .iter()
        .position(|candidate| *candidate == name)
        .ok_or("Unknown v1 event name")? as u8;
    let mut input = EventInput {
        idx,
        payload,
        first: true,
    };
    Decode::decode(&mut input)
}

/// Event codec parameterized by route header.
/// `R = RouteIdx` → v2 SailsHeader-based decoding.
/// `R = RouteName` → v1 SCALE-string variant-name decoding.
#[cfg(not(target_arch = "wasm32"))]
pub trait Event<R = RouteIdx>: Sized
where
    R: RouteHeader,
{
    fn decode_event(
        route: &R,
        payload: impl AsRef<[u8]>,
    ) -> Result<Self, parity_scale_codec::Error>;
}

#[cfg(test)]
mod tests {
    use super::*;
    // Define Add with InterfaceId to test 3-arg macro (Service mode)
    io_struct_impl!(Add (value: u32) -> u32, 0, InterfaceId::from_bytes_8([1, 2, 3, 4, 5, 6, 7, 8]));
    // Define Value with 2-arg macro (Ctor/Legacy mode)
    io_struct_impl!(Value () -> u32, 1);
    // Define Sub with `throws` type
    io_struct_impl!(Sub (value: u32) -> u32 | String, 0, InterfaceId::from_bytes_8([1, 2, 3, 4, 5, 6, 7, 8]));

    #[test]
    fn test_io_struct_impl() {
        // Add is a "Service" method, encode takes RouteIdx
        let route_idx = RouteIdx(5u8);
        let add_specific = Add::encode_call(route_idx.0, 42);

        let expected_header_add = [
            0x47, 0x4D, // magic ("GM")
            1,    // version
            16,   // hlen
            1, 2, 3, 4, 5, 6, 7, 8, // interface_id
            0, 0, // entry_id (0 for Add)
            5, // route_id
            0, // reserved
        ];
        let expected_add_payload = [42, 0, 0, 0]; // 42u32 LE

        let mut expected_add_specific = Vec::new();
        expected_add_specific.extend_from_slice(&expected_header_add);
        expected_add_specific.extend_from_slice(&expected_add_payload);

        assert_eq!(add_specific, expected_add_specific);

        let reply_payload = [42, 0, 0, 0];
        let mut reply_with_header = expected_add_specific.clone();
        reply_with_header.truncate(16);
        reply_with_header.extend_from_slice(&reply_payload);

        let decoded = Add::decode_reply(route_idx.0, &reply_with_header).unwrap();
        assert_eq!(decoded, 42);

        // Value is "Ctor" mode, it uses InterfaceId::zero()
        let value_encoded = Value::encode_call(0);
        let expected_header_value = [
            0x47, 0x4D, 1, 16, // magic, version, hlen
            0, 0, 0, 0, 0, 0, 0, 0, // interface_id (zero)
            1, 0, // entry_id (1 for Value)
            0, 0, // route_id 0 and reserved 0
        ];
        assert_eq!(value_encoded, expected_header_value);

        // Decode reply for Value
        let mut value_reply = expected_header_value.to_vec();
        value_reply.extend_from_slice(&[123, 0, 0, 0]); // payload 123u32
        let decoded_value = Value::decode_reply(0, &value_reply).unwrap();
        assert_eq!(decoded_value, 123);
    }

    #[test]
    fn test_io_struct_impl_throws() {
        let route_idx = RouteIdx(5u8);
        let sub_specific = Sub::encode_call(route_idx.0, 42);

        let expected_header_sub = [
            0x47, 0x4D, // magic ("GM")
            1,    // version
            16,   // hlen
            1, 2, 3, 4, 5, 6, 7, 8, // interface_id
            0, 0, // entry_id (0 for Sub)
            5, // route_id
            0, // reserved
        ];
        let expected_sub_payload = [42, 0, 0, 0]; // 42u32 LE

        let mut expected_sub_specific = Vec::new();
        expected_sub_specific.extend_from_slice(&expected_header_sub);
        expected_sub_specific.extend_from_slice(&expected_sub_payload);

        assert_eq!(sub_specific, expected_sub_specific);

        let mut success_reply = expected_header_sub.to_vec();
        success_reply.extend_from_slice(&expected_sub_payload);

        let decoded_success =
            <Sub as ServiceCall>::decode_reply(&route_idx, &success_reply).unwrap();
        assert_eq!(decoded_success, Ok(42));
        assert_eq!(Sub::decode_reply(route_idx.0, &success_reply).unwrap(), 42);

        let error_message = String::from("boom");
        let mut error_reply = expected_header_sub.to_vec();
        error_reply.extend_from_slice(&error_message.encode());

        let decoded_error = <Sub as ServiceCall>::decode_error(&route_idx, &error_reply).unwrap();
        assert_eq!(decoded_error, Err(error_message));
    }

    #[test]
    fn test_io_struct_impl_v1() {
        io_struct_impl_v1!(DoThis (value: u32) -> u32);

        // Encoding: SCALE("MyService") + SCALE("DoThis") + SCALE(42u32)
        let encoded = DoThis::encode_call("MyService", 42u32);
        let mut expected = Vec::new();
        "MyService".encode_to(&mut expected);
        "DoThis".encode_to(&mut expected);
        42u32.encode_to(&mut expected);
        assert_eq!(encoded, expected);

        // Decoding
        let decoded = DoThis::decode_reply("MyService", &encoded).unwrap();
        assert_eq!(decoded, 42u32);
    }
}