subxt 0.51.0

Interact with Substrate based chains on the Polkadot Network
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
// Copyright 2019-2026 Parity Technologies (UK) Ltd.
// This file is dual-licensed as Apache-2.0 or GPL-3.0.
// see LICENSE for license details.

use super::{Config, HashFor, TransactionExtensions, transaction_extensions};
use crate::config::transaction_extension_traits::Params;
use crate::config::transaction_extensions::CheckMortalityParams;
use crate::error::TransactionExtensionError;
use crate::transactions::DefaultParams;
use derive_where::derive_where;
use scale_encode::EncodeAsType;
use scale_info::PortableRegistry;
use scale_value::Value;
use std::collections::{BTreeMap, btree_map::Entry};

/// The known transaction extensions used by [`DefaultTransactionExtensions`].
///
/// This is exposed for users who need to manually compose the default typed extensions.
pub type KnownDefaultTransactionExtensions<T> = (
    transaction_extensions::VerifySignature<T>,
    transaction_extensions::CheckSpecVersion,
    transaction_extensions::CheckTxVersion,
    transaction_extensions::CheckNonce,
    transaction_extensions::CheckGenesis<T>,
    transaction_extensions::CheckMortality<T>,
    transaction_extensions::ChargeAssetTxPayment<T>,
    transaction_extensions::ChargeTransactionPayment,
    transaction_extensions::CheckMetadataHash,
);

/// The parameters used to construct [`KnownDefaultTransactionExtensions`].
pub type KnownDefaultExtrinsicParams<T> =
    <KnownDefaultTransactionExtensions<T> as TransactionExtensions<T>>::Params;

/// The default set of transaction extensions, along with any custom extensions supplied for a
/// specific transaction.
pub struct DefaultTransactionExtensions<T: Config> {
    known: KnownDefaultTransactionExtensions<T>,
    custom: BTreeMap<String, Value>,
}

/// Parameters used to construct [`DefaultTransactionExtensions`].
#[derive_where(Debug)]
pub struct DefaultExtrinsicParams<T: Config> {
    known: KnownDefaultExtrinsicParams<T>,
    custom: Vec<(String, Value)>,
}

impl<T: Config> DefaultExtrinsicParams<T> {
    /// Construct parameters from the known default transaction extension parameters.
    pub fn from_known(known: KnownDefaultExtrinsicParams<T>) -> Self {
        Self {
            known,
            custom: Vec::new(),
        }
    }

    /// Return the parameters for the known default transaction extensions.
    pub fn known(&self) -> &KnownDefaultExtrinsicParams<T> {
        &self.known
    }

    /// Return a mutable reference to the parameters for the known default
    /// transaction extensions.
    pub fn known_mut(&mut self) -> &mut KnownDefaultExtrinsicParams<T> {
        &mut self.known
    }

    /// Return the values provided for custom transaction extensions.
    pub fn custom(&self) -> &[(String, Value)] {
        &self.custom
    }
}

impl<T: Config> Default for DefaultExtrinsicParams<T> {
    fn default() -> Self {
        DefaultExtrinsicParamsBuilder::new().build()
    }
}

impl<T: Config> DefaultParams for DefaultExtrinsicParams<T> {
    fn default_params() -> Self {
        Self::default()
    }
}

impl<T: Config> Params<T> for DefaultExtrinsicParams<T> {
    fn inject_account_nonce(&mut self, nonce: u64) {
        self.known.inject_account_nonce(nonce);
    }

    fn inject_block(&mut self, number: u64, hash: HashFor<T>) {
        self.known.inject_block(number, hash);
    }
}

impl<T: Config> TransactionExtensions<T> for DefaultTransactionExtensions<T> {
    type Params = DefaultExtrinsicParams<T>;

    fn new(
        client: &super::ClientState<T>,
        params: Self::Params,
    ) -> Result<Self, TransactionExtensionError> {
        let known = <KnownDefaultTransactionExtensions<T> as TransactionExtensions<T>>::new(
            client,
            params.known,
        )?;
        let types = client.metadata.types();
        let mut custom = BTreeMap::new();

        for (name, value) in params.custom {
            if frame_decode::extrinsics::TransactionExtensions::contains_extension(&known, &name) {
                return Err(TransactionExtensionError::custom(format!(
                    "Custom transaction extension '{name}' conflicts with a known transaction extension"
                )));
            }
            // Encoding may pick any declared extension version, so a name declared in
            // any of them is accepted; a mismatch with the version ultimately chosen
            // still fails loudly at encode time.
            let newest_version = client
                .metadata
                .extrinsic()
                .transaction_extension_version_to_use_for_encoding();
            let entries: Vec<_> = (0..=newest_version)
                .filter_map(|version| {
                    client
                        .metadata
                        .extrinsic()
                        .transaction_extensions_by_version(version)
                })
                .flatten()
                .filter(|extension| extension.identifier() == name)
                .collect();
            if entries.is_empty() {
                return Err(TransactionExtensionError::custom(format!(
                    "Custom transaction extension '{name}' is not present in the runtime metadata"
                )));
            }
            if !entries
                .iter()
                .any(|extension| is_type_empty(extension.additional_ty(), types))
            {
                return Err(TransactionExtensionError::custom(format!(
                    "Custom transaction extension '{name}' requires non-empty implicit data, which is not supported"
                )));
            }
            let mut encode_result = Ok(());
            for extension in &entries {
                encode_result =
                    value.encode_as_type_to(extension.extra_ty(), types, &mut Vec::new());
                if encode_result.is_ok() {
                    break;
                }
            }
            encode_result.map_err(|error| {
                TransactionExtensionError::custom(format!(
                    "The value given for the custom transaction extension '{name}' does not encode to the type declared in the runtime metadata: {error}"
                ))
            })?;
            match custom.entry(name) {
                Entry::Occupied(entry) => {
                    return Err(TransactionExtensionError::custom(format!(
                        "Custom transaction extension '{}' was provided more than once",
                        entry.key()
                    )));
                }
                Entry::Vacant(entry) => {
                    entry.insert(value);
                }
            }
        }

        Ok(Self { known, custom })
    }

    fn inject_signature(&mut self, account_id: &T::AccountId, signature: &T::Signature) {
        self.known.inject_signature(account_id, signature);
    }
}

/// Whether a type encodes to zero bytes; mirrors the check frame-decode uses to skip
/// extensions when encoding, so a value given for a skipped extension is rejected up front.
fn is_type_empty(type_id: u32, types: &PortableRegistry) -> bool {
    let Some(ty) = types.resolve(type_id) else {
        return false;
    };
    match &ty.type_def {
        scale_info::TypeDef::Composite(composite) => composite
            .fields
            .iter()
            .all(|field| is_type_empty(field.ty.id, types)),
        scale_info::TypeDef::Tuple(tuple) => tuple
            .fields
            .iter()
            .all(|field| is_type_empty(field.id, types)),
        scale_info::TypeDef::Array(array) => {
            array.len == 0 || is_type_empty(array.type_param.id, types)
        }
        _ => false,
    }
}

impl<T: Config> DefaultTransactionExtensions<T> {
    fn encode_custom_value_to(
        &self,
        name: &str,
        type_id: u32,
        type_resolver: &PortableRegistry,
        out: &mut Vec<u8>,
    ) -> Result<(), frame_decode::extrinsics::TransactionExtensionsError> {
        let value = self.custom.get(name).ok_or_else(|| {
            frame_decode::extrinsics::TransactionExtensionsError::NotFound(name.to_owned())
        })?;
        let original_len = out.len();
        let result = value.encode_as_type_to(type_id, type_resolver, out);
        result.map_err(|error| {
            out.truncate(original_len);
            frame_decode::extrinsics::TransactionExtensionsError::Other {
                extension_name: name.to_owned(),
                error: Box::new(error),
            }
        })
    }
}

impl<T: Config> frame_decode::extrinsics::TransactionExtensions<PortableRegistry>
    for DefaultTransactionExtensions<T>
{
    fn contains_extension(&self, name: &str) -> bool {
        frame_decode::extrinsics::TransactionExtensions::contains_extension(&self.known, name)
            || self.custom.contains_key(name)
    }

    // Only the known extensions can authorize a transaction; a chain-specific extension
    // supplied via `custom_extension` always reports `false` here. See
    // https://github.com/paritytech/subxt/issues/2276.
    fn is_authorization_extension(&self, name: &str) -> bool {
        frame_decode::extrinsics::TransactionExtensions::is_authorization_extension(
            &self.known,
            name,
        )
    }

    fn encode_extension_value_to(
        &self,
        name: &str,
        type_id: u32,
        type_resolver: &PortableRegistry,
        out: &mut Vec<u8>,
    ) -> Result<(), frame_decode::extrinsics::TransactionExtensionsError> {
        if frame_decode::extrinsics::TransactionExtensions::contains_extension(&self.known, name) {
            frame_decode::extrinsics::TransactionExtensions::encode_extension_value_to(
                &self.known,
                name,
                type_id,
                type_resolver,
                out,
            )
        } else {
            self.encode_custom_value_to(name, type_id, type_resolver, out)
        }
    }

    fn encode_extension_implicit_to(
        &self,
        name: &str,
        type_id: u32,
        type_resolver: &PortableRegistry,
        out: &mut Vec<u8>,
    ) -> Result<(), frame_decode::extrinsics::TransactionExtensionsError> {
        if frame_decode::extrinsics::TransactionExtensions::contains_extension(&self.known, name) {
            frame_decode::extrinsics::TransactionExtensions::encode_extension_implicit_to(
                &self.known,
                name,
                type_id,
                type_resolver,
                out,
            )
        } else if self.custom.contains_key(name) {
            Err(frame_decode::extrinsics::TransactionExtensionsError::Other {
                extension_name: name.to_owned(),
                error: format!(
                    "Custom transaction extension '{name}' requires non-empty implicit data, which is not supported"
                )
                .into(),
            })
        } else {
            Err(frame_decode::extrinsics::TransactionExtensionsError::NotFound(name.to_owned()))
        }
    }
}

/// A builder that outputs the set of parameters required to configure transactions when
/// [`DefaultTransactionExtensions`] is used. This may expose methods that aren't applicable
/// to the current chain; such values will simply be ignored if so.
pub struct DefaultExtrinsicParamsBuilder<T: Config> {
    /// `None` means the tx will be immortal, else it's mortality is described.
    mortality: transaction_extensions::CheckMortalityParams<T>,
    /// `None` means the nonce will be automatically set.
    nonce: Option<u64>,
    /// `None` means we'll use the native token.
    tip_of_asset_id: Option<T::AssetId>,
    tip_of: u128,
    /// A fallback tip used when no Asset ID is given (or the chain doesn't support it).
    tip: u128,
    custom: Vec<(String, Value)>,
}

impl<T: Config> Default for DefaultExtrinsicParamsBuilder<T> {
    fn default() -> Self {
        Self {
            mortality: CheckMortalityParams::<T>::default(),
            tip: 0,
            tip_of: 0,
            tip_of_asset_id: None,
            nonce: None,
            custom: Vec::new(),
        }
    }
}

impl<T: Config> DefaultExtrinsicParamsBuilder<T> {
    /// Configure new extrinsic params. We default to providing no tip
    /// and using an immortal transaction unless otherwise configured
    pub fn new() -> Self {
        Default::default()
    }

    /// Make the transaction immortal, meaning it will never expire. This means that it could, in
    /// theory, be pending for a long time and only be included many blocks into the future.
    pub fn immortal(mut self) -> Self {
        self.mortality = transaction_extensions::CheckMortalityParams::<T>::immortal();
        self
    }

    /// Make the transaction mortal, given a number of blocks it will be mortal for from
    /// the current block at the time of submission.
    ///
    /// # Warning
    ///
    /// This will ultimately return an error if used for creating extrinsic offline, because we need
    /// additional information in order to set the mortality properly.
    ///
    /// When creating offline transactions, you must use [`Self::mortal_from_unchecked`] instead to set
    /// the mortality. This provides all of the necessary information which we must otherwise be online
    /// in order to obtain.
    pub fn mortal(mut self, for_n_blocks: u64) -> Self {
        self.mortality = transaction_extensions::CheckMortalityParams::<T>::mortal(for_n_blocks);
        self
    }

    /// Configure a transaction that will be mortal for the number of blocks given, and from the
    /// block details provided. Prefer to use [`Self::mortal()`] where possible, which prevents
    /// the block number and hash from being misaligned.
    pub fn mortal_from_unchecked(
        mut self,
        for_n_blocks: u64,
        from_block_n: u64,
        from_block_hash: HashFor<T>,
    ) -> Self {
        self.mortality = transaction_extensions::CheckMortalityParams::mortal_from_unchecked(
            for_n_blocks,
            from_block_n,
            from_block_hash,
        );
        self
    }

    /// Provide a specific nonce for the submitter of the extrinsic
    pub fn nonce(mut self, nonce: u64) -> Self {
        self.nonce = Some(nonce);
        self
    }

    /// Provide a tip to the block author in the chain's native token.
    pub fn tip(mut self, tip: u128) -> Self {
        self.tip = tip;
        self.tip_of = tip;
        self.tip_of_asset_id = None;
        self
    }

    /// Provide a tip to the block author using the token denominated by the `asset_id` provided. This
    /// is not applicable on chains which don't use the `ChargeAssetTxPayment` signed extension; in this
    /// case, you can also call [`Self::tip`] to configure a tip in the native asset in case this is not
    /// applicable.
    pub fn tip_of(mut self, tip: u128, asset_id: T::AssetId) -> Self {
        self.tip_of = tip;
        self.tip_of_asset_id = Some(asset_id);
        self
    }

    /// Provide a metadata-aware value for a custom transaction extension.
    ///
    /// This is for extensions that a chain declares but Subxt has no typed support for; the
    /// value given here is encoded using the type information in the runtime metadata.
    ///
    /// Extensions absent from runtime metadata are rejected, as are known or duplicate names,
    /// values that don't encode to the type the metadata declares for the extension, and
    /// extensions with non-empty implicit data. Custom authorization extensions are
    /// unsupported.
    ///
    /// # Example
    ///
    /// ```rust
    /// use subxt::config::{DefaultExtrinsicParamsBuilder, PolkadotConfig};
    ///
    /// // The name must match an extension identifier in the chain's metadata, and the value
    /// // must encode to the type that the metadata declares for it.
    /// let params = DefaultExtrinsicParamsBuilder::<PolkadotConfig>::new()
    ///     .tip(100)
    ///     .custom_extension("MyCustomExtension", true)
    ///     .build();
    ///
    /// assert_eq!(params.custom(), [("MyCustomExtension".to_owned(), true.into())]);
    /// ```
    pub fn custom_extension(mut self, name: impl Into<String>, value: impl Into<Value>) -> Self {
        self.custom.push((name.into(), value.into()));
        self
    }

    /// Build the extrinsic parameters.
    pub fn build(self) -> DefaultExtrinsicParams<T> {
        let check_mortality_params = self.mortality;

        let charge_asset_tx_params = if let Some(asset_id) = self.tip_of_asset_id {
            transaction_extensions::ChargeAssetTxPaymentParams::tip_of(self.tip_of, asset_id)
        } else {
            transaction_extensions::ChargeAssetTxPaymentParams::tip(self.tip_of)
        };

        let charge_transaction_params =
            transaction_extensions::ChargeTransactionPaymentParams::tip(self.tip);

        let check_nonce_params = if let Some(nonce) = self.nonce {
            transaction_extensions::CheckNonceParams::with_nonce(nonce)
        } else {
            transaction_extensions::CheckNonceParams::from_chain()
        };

        DefaultExtrinsicParams {
            known: (
                (),
                (),
                (),
                check_nonce_params,
                (),
                check_mortality_params,
                charge_asset_tx_params,
                charge_transaction_params,
                (),
            ),
            custom: self.custom,
        }
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use crate::config::polkadot::H256;
    use crate::config::{ClientState, PolkadotConfig};
    use crate::metadata::Metadata;
    use crate::utils::{AccountId32, MultiSignature};
    use assert_matches::assert_matches;
    use codec::Decode;
    use frame_decode::extrinsics::{
        ExtrinsicCallInfo, ExtrinsicEncodeError, ExtrinsicExtensionInfo, ExtrinsicExtensionInfoArg,
        ExtrinsicSignatureInfo, TransactionExtensionsError,
    };
    use scale_info::{MetaType, Registry};
    use scale_value::Composite;
    use std::borrow::Cow;
    use std::sync::Arc;

    fn assert_default<T: Default>(_t: T) {}

    /// Mirrors `VerifySignatureDetails`, which is what the `VerifyMultiSignature`
    /// extension encodes into.
    #[allow(dead_code)]
    #[derive(scale_info::TypeInfo)]
    enum SignatureDetails {
        Signed {
            signature: MultiSignature,
            account: AccountId32,
        },
        Disabled,
    }

    fn client_state() -> ClientState<PolkadotConfig> {
        ClientState {
            genesis_hash: H256::zero(),
            spec_version: 0,
            transaction_version: 0,
            metadata: Arc::new(test_metadata()),
        }
    }

    /// Metadata declaring the extensions these tests pass as custom values, typed to
    /// match the fabricated encoding info. `WithImplicit` exercises the rejection of
    /// custom extensions whose implicit data is non-empty.
    fn test_metadata() -> Metadata {
        use frame_metadata::v16;
        use scale_info::meta_type;

        let transaction_extensions = vec![
            v16::TransactionExtensionMetadata {
                identifier: "CheckWeight",
                ty: meta_type::<bool>(),
                implicit: meta_type::<()>(),
            },
            v16::TransactionExtensionMetadata {
                identifier: "WeightReclaim",
                ty: meta_type::<bool>(),
                implicit: meta_type::<()>(),
            },
            v16::TransactionExtensionMetadata {
                identifier: "WithImplicit",
                ty: meta_type::<bool>(),
                implicit: meta_type::<u32>(),
            },
        ];
        let extension_indexes = (0..transaction_extensions.len() as u32)
            .map(codec::Compact)
            .collect();

        v16::RuntimeMetadataV16::new(
            Vec::new(),
            v16::ExtrinsicMetadata {
                versions: vec![4, 5],
                address_ty: meta_type::<u8>(),
                call_ty: meta_type::<()>(),
                signature_ty: meta_type::<u8>(),
                transaction_extensions_by_version: [(0u8, extension_indexes)].into_iter().collect(),
                transaction_extensions,
            },
            Vec::new(),
            v16::OuterEnums {
                call_enum_ty: meta_type::<()>(),
                event_enum_ty: meta_type::<()>(),
                error_enum_ty: meta_type::<()>(),
            },
            v16::CustomMetadata {
                map: Default::default(),
            },
        )
        .try_into()
        .expect("can build valid metadata")
    }

    fn type_info<T: scale_info::TypeInfo + 'static>() -> (u32, PortableRegistry) {
        let mut types = Registry::new();
        let id = types.register_type(&MetaType::new::<T>());
        (id.id, types.into())
    }

    fn encoding_info() -> (
        ExtrinsicCallInfo<'static, u32>,
        ExtrinsicExtensionInfo<'static, u32>,
        ExtrinsicSignatureInfo<u32>,
        PortableRegistry,
    ) {
        let mut types = Registry::new();
        let bool_id = types.register_type(&MetaType::new::<bool>()).id;
        let unit_id = types.register_type(&MetaType::new::<()>()).id;
        let u8_id = types.register_type(&MetaType::new::<u8>()).id;

        (
            ExtrinsicCallInfo {
                pallet_index: 1,
                call_index: 2,
                pallet_name: Cow::Borrowed("Test"),
                call_name: Cow::Borrowed("call"),
                args: Vec::new(),
            },
            ExtrinsicExtensionInfo {
                extension_ids: vec![ExtrinsicExtensionInfoArg {
                    name: Cow::Borrowed("CheckWeight"),
                    id: bool_id,
                    implicit_id: unit_id,
                }],
            },
            ExtrinsicSignatureInfo {
                address_id: u8_id,
                signature_id: u8_id,
            },
            types.into(),
        )
    }

    fn v5_encoding_info() -> (
        ExtrinsicCallInfo<'static, u32>,
        ExtrinsicExtensionInfo<'static, u32>,
        PortableRegistry,
    ) {
        let mut types = Registry::new();
        let bool_id = types.register_type(&MetaType::new::<bool>()).id;
        let unit_id = types.register_type(&MetaType::new::<()>()).id;
        let signature_id = types.register_type(&MetaType::new::<SignatureDetails>()).id;

        (
            ExtrinsicCallInfo {
                pallet_index: 1,
                call_index: 2,
                pallet_name: Cow::Borrowed("Test"),
                call_name: Cow::Borrowed("call"),
                args: Vec::new(),
            },
            // `CheckWeight` sits before the authorization extension and `WeightReclaim`
            // after it, so the extrinsic must carry a value from either side.
            ExtrinsicExtensionInfo {
                extension_ids: vec![
                    ExtrinsicExtensionInfoArg {
                        name: Cow::Borrowed("CheckWeight"),
                        id: bool_id,
                        implicit_id: unit_id,
                    },
                    ExtrinsicExtensionInfoArg {
                        name: Cow::Borrowed("VerifyMultiSignature"),
                        id: signature_id,
                        implicit_id: unit_id,
                    },
                    ExtrinsicExtensionInfoArg {
                        name: Cow::Borrowed("WeightReclaim"),
                        id: bool_id,
                        implicit_id: unit_id,
                    },
                ],
            },
            types.into(),
        )
    }

    #[test]
    fn params_are_default() {
        let params = DefaultExtrinsicParamsBuilder::<PolkadotConfig>::new().build();
        assert_default(params)
    }

    #[test]
    fn unknown_extension_without_custom_value_still_errors() {
        let params = DefaultExtrinsicParamsBuilder::<PolkadotConfig>::new().build();
        let extensions = DefaultTransactionExtensions::new(&client_state(), params).unwrap();
        let (call_info, extension_info, _, types) = encoding_info();
        let call_data = Composite::<()>::Unnamed(Vec::new());

        let error = frame_decode::extrinsics::encode_v4_signer_payload_with_info(
            &call_data,
            &extensions,
            &types,
            &call_info,
            &extension_info,
        )
        .unwrap_err();

        assert_matches!(
            error,
            ExtrinsicEncodeError::TransactionExtensions(TransactionExtensionsError::NotFound(name))
                if name == "CheckWeight"
        );
    }

    #[test]
    fn authorization_extension_check_is_forwarded() {
        let params = DefaultExtrinsicParamsBuilder::<PolkadotConfig>::new()
            .custom_extension("CheckWeight", true)
            .build();
        let extensions = DefaultTransactionExtensions::new(&client_state(), params).unwrap();
        assert!(
            frame_decode::extrinsics::TransactionExtensions::is_authorization_extension(
                &extensions,
                "VerifyMultiSignature"
            )
        );
        // Custom extensions are never authorization extensions.
        assert!(
            !frame_decode::extrinsics::TransactionExtensions::is_authorization_extension(
                &extensions,
                "CheckWeight"
            )
        );
        // Neither is a known non-authorization extension, nor a name we don't hold at all.
        assert!(
            !frame_decode::extrinsics::TransactionExtensions::is_authorization_extension(
                &extensions,
                "CheckNonce"
            )
        );
        assert!(
            !frame_decode::extrinsics::TransactionExtensions::is_authorization_extension(
                &extensions,
                "Unknown"
            )
        );
    }

    #[test]
    fn signature_injection_is_forwarded() {
        let params = DefaultExtrinsicParamsBuilder::<PolkadotConfig>::new().build();
        let mut extensions = DefaultTransactionExtensions::new(&client_state(), params).unwrap();
        extensions.inject_signature(
            &AccountId32::from([1; 32]),
            &MultiSignature::Sr25519([2; 64]),
        );
        let (type_id, types) = type_info::<SignatureDetails>();
        let mut out = Vec::new();

        frame_decode::extrinsics::TransactionExtensions::encode_extension_value_to(
            &extensions,
            "VerifyMultiSignature",
            type_id,
            &types,
            &mut out,
        )
        .unwrap();

        let mut expected = vec![0, 1];
        expected.extend([2; 64]);
        expected.extend([1; 32]);
        assert_eq!(out, expected);
    }

    #[test]
    fn params_forward_injected_nonce_and_block() {
        let mut params = DefaultExtrinsicParamsBuilder::<PolkadotConfig>::new()
            .custom_extension("CheckWeight", true)
            .build();
        params.inject_account_nonce(7);
        params.inject_block(10, H256::repeat_byte(1));
        let extensions = DefaultTransactionExtensions::new(&client_state(), params).unwrap();
        let mut nonce = Vec::new();
        let mut mortality = Vec::new();
        let (_, types) = type_info::<bool>();

        frame_decode::extrinsics::TransactionExtensions::encode_extension_value_to(
            &extensions,
            "CheckNonce",
            0,
            &types,
            &mut nonce,
        )
        .unwrap();
        frame_decode::extrinsics::TransactionExtensions::encode_extension_value_to(
            &extensions,
            "CheckMortality",
            0,
            &types,
            &mut mortality,
        )
        .unwrap();

        assert_eq!(nonce, [28]);
        assert_ne!(mortality, [0]);
    }

    #[test]
    fn custom_extension_cannot_override_known_extension() {
        let params = DefaultExtrinsicParamsBuilder::<PolkadotConfig>::new()
            .custom_extension("CheckNonce", 1u128)
            .build();

        let error = DefaultTransactionExtensions::new(&client_state(), params)
            .err()
            .unwrap();

        assert!(error.to_string().contains("conflicts with a known"));
    }

    #[test]
    fn custom_extension_name_cannot_be_repeated() {
        let params = DefaultExtrinsicParamsBuilder::<PolkadotConfig>::new()
            .custom_extension("CheckWeight", true)
            .custom_extension("CheckWeight", false)
            .build();

        let error = DefaultTransactionExtensions::new(&client_state(), params)
            .err()
            .unwrap();

        assert!(error.to_string().contains("provided more than once"));
    }

    #[test]
    fn contains_known_and_custom_extensions() {
        let params = DefaultExtrinsicParamsBuilder::<PolkadotConfig>::new()
            .custom_extension("CheckWeight", true)
            .build();
        let extensions = DefaultTransactionExtensions::new(&client_state(), params).unwrap();

        assert!(
            frame_decode::extrinsics::TransactionExtensions::contains_extension(
                &extensions,
                "CheckNonce"
            )
        );
        assert!(
            frame_decode::extrinsics::TransactionExtensions::contains_extension(
                &extensions,
                "CheckWeight"
            )
        );
        assert!(
            !frame_decode::extrinsics::TransactionExtensions::contains_extension(
                &extensions,
                "Unknown"
            )
        );
    }

    #[test]
    fn nonempty_custom_implicit_has_a_specific_error() {
        let params = DefaultExtrinsicParamsBuilder::<PolkadotConfig>::new()
            .custom_extension("WeightReclaim", true)
            .build();
        let extensions = DefaultTransactionExtensions::new(&client_state(), params).unwrap();
        let (type_id, types) = type_info::<u32>();
        let mut out = Vec::new();

        let error = frame_decode::extrinsics::TransactionExtensions::encode_extension_implicit_to(
            &extensions,
            "WeightReclaim",
            type_id,
            &types,
            &mut out,
        )
        .unwrap_err();

        assert!(
            error
                .to_string()
                .contains("requires non-empty implicit data")
        );
    }

    #[test]
    fn custom_extension_with_nonempty_implicit_is_rejected() {
        let params = DefaultExtrinsicParamsBuilder::<PolkadotConfig>::new()
            .custom_extension("WithImplicit", true)
            .build();

        let error = DefaultTransactionExtensions::new(&client_state(), params)
            .err()
            .unwrap();

        assert!(
            error
                .to_string()
                .contains("requires non-empty implicit data")
        );
    }

    #[test]
    fn custom_extension_value_of_wrong_type_is_rejected() {
        let params = DefaultExtrinsicParamsBuilder::<PolkadotConfig>::new()
            .custom_extension("CheckWeight", Value::u128(1))
            .build();

        let error = DefaultTransactionExtensions::new(&client_state(), params)
            .err()
            .unwrap();

        assert!(
            error
                .to_string()
                .contains("does not encode to the type declared in the runtime metadata")
        );
    }

    #[test]
    fn custom_encoding_error_does_not_modify_output() {
        let params = DefaultExtrinsicParamsBuilder::<PolkadotConfig>::new()
            .custom_extension("WeightReclaim", true)
            .build();
        let extensions = DefaultTransactionExtensions::new(&client_state(), params).unwrap();
        let (type_id, types) = type_info::<u32>();
        let mut out = vec![42];

        let error = frame_decode::extrinsics::TransactionExtensions::encode_extension_value_to(
            &extensions,
            "WeightReclaim",
            type_id,
            &types,
            &mut out,
        )
        .unwrap_err();

        assert_eq!(out, [42]);
        assert_matches!(
            error,
            TransactionExtensionsError::Other { extension_name, .. }
                if extension_name == "WeightReclaim"
        );
    }

    #[test]
    fn custom_extension_is_used_in_v4_payload_and_extrinsic() {
        let params = DefaultExtrinsicParamsBuilder::<PolkadotConfig>::new()
            .custom_extension("CheckWeight", true)
            .build();
        let extensions = DefaultTransactionExtensions::new(&client_state(), params).unwrap();
        let (call_info, extension_info, signature_info, types) = encoding_info();
        let call_data = Composite::<()>::Unnamed(Vec::new());

        let payload = frame_decode::extrinsics::encode_v4_signer_payload_with_info(
            &call_data,
            &extensions,
            &types,
            &call_info,
            &extension_info,
        )
        .unwrap();
        let mut extrinsic = Vec::new();
        frame_decode::extrinsics::encode_v4_signed_with_info_to(
            &call_data,
            &extensions,
            &3u8,
            &4u8,
            &types,
            &call_info,
            &signature_info,
            &extension_info,
            &mut extrinsic,
        )
        .unwrap();
        let inner = Vec::<u8>::decode(&mut &*extrinsic).unwrap();

        assert_eq!(payload, [1, 2, 1]);
        assert_eq!(inner, [0x84, 3, 4, 1, 1, 2]);
    }

    #[test]
    fn custom_extension_absent_from_metadata_is_rejected() {
        let params = DefaultExtrinsicParamsBuilder::<PolkadotConfig>::new()
            .custom_extension("ChckWeight", true)
            .build();

        let error = DefaultTransactionExtensions::new(&client_state(), params)
            .err()
            .unwrap();

        assert!(
            error
                .to_string()
                .contains("is not present in the runtime metadata")
        );
    }

    #[test]
    fn v5_general_extrinsic_includes_custom_extensions_either_side_of_authorization() {
        let params = DefaultExtrinsicParamsBuilder::<PolkadotConfig>::new()
            .custom_extension("CheckWeight", true)
            .custom_extension("WeightReclaim", false)
            .build();
        let extensions = DefaultTransactionExtensions::new(&client_state(), params).unwrap();
        let (call_info, extension_info, types) = v5_encoding_info();
        let call_data = Composite::<()>::Unnamed(Vec::new());
        let mut extrinsic = Vec::new();

        frame_decode::extrinsics::encode_v5_general_with_info_to(
            &call_data,
            0,
            &extensions,
            &types,
            &call_info,
            &extension_info,
            &mut extrinsic,
        )
        .unwrap();
        let inner = Vec::<u8>::decode(&mut &*extrinsic).unwrap();
        assert_eq!(
            inner,
            [
                0b0100_0000 + 5, // Preamble: "general" transaction, extrinsic version 5
                0,               // Transaction extension version
                1,               // CheckWeight: true
                1,               // VerifyMultiSignature: Disabled (variant index 1)
                0,               // WeightReclaim: false
                1,               // Pallet index
                2,               // Call index
            ]
        );
    }

    #[test]
    fn tip_of_sets_correct_tip_on_charge_asset_tx_payment() {
        let params = DefaultExtrinsicParamsBuilder::<PolkadotConfig>::new()
            .tip(100) // Set the "basic" tip for ChargeTransactionPayment
            .tip_of(200, 42) // Set the asset-based tip for ChargeAssetTxPayment
            .build();

        // Type signatures here ensure we're getting the params we think we are:
        let known = params.known();
        let charge_asset_params: &transaction_extensions::ChargeAssetTxPaymentParams<_> = &known.6;
        let charge_transaction_params: &transaction_extensions::ChargeTransactionPaymentParams =
            &known.7;

        // Verify that the params are properly set:
        assert_eq!(
            *charge_asset_params,
            transaction_extensions::ChargeAssetTxPaymentParams::tip_of(200, 42)
        );
        assert_eq!(
            *charge_transaction_params,
            transaction_extensions::ChargeTransactionPaymentParams::tip(100)
        )
    }
}