subxt 0.50.3

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
//! This module exposes [`TransactionsClient`], which has methods for constructing and submitting
//! transactions. It's created by calling [`crate::client::ClientAtBlock::transactions()`], or
//! [`crate::client::ClientAtBlock::tx()`] for short.

mod account_nonce;
mod default_params;
mod payload;
mod signer;
mod transaction_progress;
mod validation_result;

use crate::backend::TransactionStatus as BackendTransactionStatus;
use crate::client::{OfflineClientAtBlockT, OnlineClientAtBlockT};
use crate::config::transaction_extensions::Params;
use crate::config::{ClientState, Config, HashFor, Hasher, TransactionExtensions};
use crate::error::{ExtrinsicError, TransactionStatusError};
use codec::{Compact, Decode, Encode};
use core::marker::PhantomData;
use scale_value::Composite;

pub use default_params::DefaultParams;
pub use payload::{DynamicPayload, Payload, StaticPayload, ValidationDetails, dynamic};
pub use signer::Signer;
pub use transaction_progress::{TransactionInBlock, TransactionProgress, TransactionStatus};
pub use validation_result::{
    TransactionInvalid, TransactionUnknown, TransactionValid, ValidationResult,
};

/// A client for working with transactions. See [the module docs](crate::transactions) for more.
#[derive(Clone)]
pub struct TransactionsClient<T, Client> {
    client: Client,
    marker: PhantomData<T>,
}

impl<T, Client> TransactionsClient<T, Client> {
    pub(crate) fn new(client: Client) -> Self {
        TransactionsClient {
            client,
            marker: PhantomData,
        }
    }
}

impl<T: Config, Client: OfflineClientAtBlockT<T>> TransactionsClient<T, Client> {
    /// Run the validation logic against some transaction you'd like to submit. Returns `Ok(())`
    /// if the call is valid (or if it's not possible to check since the call has no validation hash).
    /// Return an error if the call was not valid or something went wrong trying to validate it (ie
    /// the pallet or call in question do not exist at all).
    pub fn validate<Call>(&self, call: &Call) -> Result<(), ExtrinsicError>
    where
        Call: Payload,
    {
        let Some(details) = call.validation_details() else {
            return Ok(());
        };

        let pallet_name = details.pallet_name;
        let call_name = details.call_name;

        let expected_hash = self
            .client
            .metadata_ref()
            .pallet_by_name(pallet_name)
            .ok_or_else(|| ExtrinsicError::PalletNameNotFound(pallet_name.to_string()))?
            .call_hash(call_name)
            .ok_or_else(|| ExtrinsicError::CallNameNotFound {
                pallet_name: pallet_name.to_string(),
                call_name: call_name.to_string(),
            })?;

        if details.hash != expected_hash {
            Err(ExtrinsicError::IncompatibleCodegen)
        } else {
            Ok(())
        }
    }

    /// Create a [`SubmittableTransaction`] from some already-signed and prepared
    /// transaction bytes, and some client (anything implementing [`OfflineClientAtBlockT`]
    /// or [`OnlineClientAtBlockT`]).
    pub fn from_bytes(&self, tx_bytes: Vec<u8>) -> SubmittableTransaction<T, Client> {
        SubmittableTransaction {
            client: self.client.clone(),
            encoded: tx_bytes,
            marker: PhantomData,
        }
    }

    /// Return the SCALE encoded bytes representing the call data of the transaction.
    pub fn call_data<Call>(&self, call: &Call) -> Result<Vec<u8>, ExtrinsicError>
    where
        Call: Payload,
    {
        let encoded = frame_decode::extrinsics::encode_call_data(
            call.pallet_name(),
            call.call_name(),
            call.call_data(),
            self.client.metadata_ref(),
            self.client.metadata_ref().types(),
        )?;

        Ok(encoded)
    }

    /// Decode SCALE encoded call data (such as the bytes handed back from
    /// [`Self::call_data()`]) into a [`DynamicPayload`], which can then be
    /// signed and submitted like any other payload. The call data is decoded
    /// against the current metadata, and an error is returned if it's not
    /// valid for the current runtime.
    pub fn from_call_data_bytes(
        &self,
        call_data: &[u8],
    ) -> Result<DynamicPayload<Composite<()>>, ExtrinsicError> {
        use frame_decode::extrinsics::ExtrinsicTypeInfo;
        use scale_decode::DecodeAsFields;

        let &[pallet_index, call_index, ..] = call_data else {
            return Err(ExtrinsicError::CallDataTooShort(call_data.len()));
        };

        let metadata = self.client.metadata_ref();
        let call_info = metadata
            .extrinsic_call_info_by_index(pallet_index, call_index)
            .map_err(|e| ExtrinsicError::CannotDecodeCallData(e.into_owned()))?;

        let mut fields = call_info.args.iter().map(|arg| {
            let name = (!arg.name.is_empty()).then_some(&*arg.name);
            scale_decode::Field::new(arg.id, name)
        });

        // The first two bytes are the pallet and call indices decoded above;
        // only the call arguments remain to be decoded here
        let cursor = &mut &call_data[2..];
        let args = Composite::<()>::decode_as_fields(cursor, &mut fields, metadata.types())
            .map_err(ExtrinsicError::CannotDecodeCallDataFields)?;

        if !cursor.is_empty() {
            return Err(ExtrinsicError::LeftoverBytesDecodingCallData(cursor.len()));
        }

        Ok(dynamic(call_info.pallet_name, call_info.call_name, args))
    }

    /// Creates an unsigned transaction without submitting it. Depending on the metadata, we might end
    /// up constructing either a v4 or v5 transaction. See [`Self::create_v4_unsigned`] or
    /// [`Self::create_v5_unsigned`] if you'd like to explicitly create an unsigned transaction of a certain version.
    pub fn create_unsigned<Call>(
        &self,
        call: &Call,
    ) -> Result<SubmittableTransaction<T, Client>, ExtrinsicError>
    where
        Call: Payload,
    {
        let tx = match self.default_transaction_version()? {
            SupportedTransactionVersion::V4 => self.create_v4_unsigned(call),
            SupportedTransactionVersion::V5 => self.create_v5_unsigned(call),
        }?;

        Ok(tx)
    }

    /// Creates a V4 "unsigned" transaction without submitting it.
    pub fn create_v4_unsigned<Call>(
        &self,
        call: &Call,
    ) -> Result<SubmittableTransaction<T, Client>, ExtrinsicError>
    where
        Call: Payload,
    {
        self.validate(call)?;

        let encoded = frame_decode::extrinsics::encode_v4_unsigned(
            call.pallet_name(),
            call.call_name(),
            call.call_data(),
            self.client.metadata_ref(),
            self.client.metadata_ref().types(),
        )?;

        Ok(SubmittableTransaction {
            client: self.client.clone(),
            encoded,
            marker: PhantomData,
        })
    }

    /// Creates a V5 "bare" transaction without submitting it.
    pub fn create_v5_unsigned<Call>(
        &self,
        call: &Call,
    ) -> Result<SubmittableTransaction<T, Client>, ExtrinsicError>
    where
        Call: Payload,
    {
        self.validate(call)?;

        let encoded = frame_decode::extrinsics::encode_v5_bare(
            call.pallet_name(),
            call.call_name(),
            call.call_data(),
            self.client.metadata_ref(),
            self.client.metadata_ref().types(),
        )?;

        Ok(SubmittableTransaction {
            client: self.client.clone(),
            encoded,
            marker: PhantomData,
        })
    }

    /// Create a signable transaction. Depending on the metadata, we might end up constructing either a v4 or
    /// v5 transaction. Use [`Self::create_v4_signable_offline`] or [`Self::create_v5_signable_offline`] if you'd
    /// like to manually use a specific version.
    ///
    /// Note: if not provided, the default account nonce will be set to 0 and the default mortality will be _immortal_.
    /// This is because this method runs offline, and so is unable to fetch the data needed for more appropriate values.
    pub fn create_signable_offline<'call, Call>(
        &self,
        call: &'call Call,
        params: <T::TransactionExtensions as TransactionExtensions<T>>::Params,
    ) -> Result<SignableTransaction<'call, T, Client, Call>, ExtrinsicError>
    where
        Call: Payload,
    {
        match self.default_transaction_version()? {
            SupportedTransactionVersion::V4 => self.create_v4_signable_offline(call, params),
            SupportedTransactionVersion::V5 => self.create_v5_signable_offline(call, params),
        }
    }

    /// Create a v4 partial transaction, ready to sign.
    ///
    /// Note: if not provided, the default account nonce will be set to 0 and the default mortality will be _immortal_.
    /// This is because this method runs offline, and so is unable to fetch the data needed for more appropriate values.
    ///
    /// Prefer [`Self::create_signable_offline()`] if you don't know which version to create; this will pick the
    /// most suitable one for the given chain.
    pub fn create_v4_signable_offline<'call, Call>(
        &self,
        call: &'call Call,
        params: <T::TransactionExtensions as TransactionExtensions<T>>::Params,
    ) -> Result<SignableTransaction<'call, T, Client, Call>, ExtrinsicError>
    where
        Call: Payload,
    {
        self.create_signable_at_version(call, params, SupportedTransactionVersion::V4)
    }

    /// Create a v5 partial transaction, ready to sign.
    ///
    /// Note: if not provided, the default account nonce will be set to 0 and the default mortality will be _immortal_.
    /// This is because this method runs offline, and so is unable to fetch the data needed for more appropriate values.
    ///
    /// Prefer [`Self::create_signable_offline()`] if you don't know which version to create; this will pick the
    /// most suitable one for the given chain.
    pub fn create_v5_signable_offline<'call, Call>(
        &self,
        call: &'call Call,
        params: <T::TransactionExtensions as TransactionExtensions<T>>::Params,
    ) -> Result<SignableTransaction<'call, T, Client, Call>, ExtrinsicError>
    where
        Call: Payload,
    {
        self.create_signable_at_version(call, params, SupportedTransactionVersion::V5)
    }

    /// Returns the suggested transaction versions to build for a given chain, or an error
    /// if Subxt doesn't support any version expected by the chain.
    ///
    /// When using methods like [`Self::create_signable_offline`] and [`Self::create_unsigned`],
    /// this will be used internally to decide which transaction version to construct.
    pub fn default_transaction_version(
        &self,
    ) -> Result<SupportedTransactionVersion, ExtrinsicError> {
        let metadata = self.client.metadata_ref();
        let versions = metadata.extrinsic().supported_versions();

        if versions.contains(&4) {
            Ok(SupportedTransactionVersion::V4)
        } else if versions.contains(&5) {
            Ok(SupportedTransactionVersion::V5)
        } else {
            Err(ExtrinsicError::UnsupportedVersion)
        }
    }

    // Create a V4 "signed" or a V5 "general" transaction.
    fn create_signable_at_version<'call, Call>(
        &self,
        call: &'call Call,
        params: <T::TransactionExtensions as TransactionExtensions<T>>::Params,
        tx_version: SupportedTransactionVersion,
    ) -> Result<SignableTransaction<'call, T, Client, Call>, ExtrinsicError>
    where
        Call: Payload,
    {
        // 1. Validate this call against the current node metadata if the call comes
        // with a hash allowing us to do so.
        self.validate(call)?;

        // 2. Work out which TX extension version to target based on metadata.
        let tx_extension_version = match tx_version {
            SupportedTransactionVersion::V4 => None,
            SupportedTransactionVersion::V5 => {
                let v = self
                    .client
                    .metadata_ref()
                    .extrinsic()
                    .transaction_extension_version_to_use_for_encoding();
                Some(v)
            }
        };

        // 4. Construct our custom additional/extra params.
        let client_state = ClientState {
            genesis_hash: self
                .client
                .genesis_hash()
                .ok_or(ExtrinsicError::GenesisHashNotProvided)?,
            spec_version: self.client.spec_version(),
            transaction_version: self.client.transaction_version(),
            metadata: self.client.metadata(),
        };
        let tx_extensions =
            <T::TransactionExtensions as TransactionExtensions<T>>::new(&client_state, params)?;

        // Return these details, ready to construct a signed extrinsic from.
        Ok(SignableTransaction {
            client: self.client.clone(),
            call,
            tx_extensions,
            tx_extension_version,
        })
    }
}

impl<T: Config, Client: OnlineClientAtBlockT<T>> TransactionsClient<T, Client> {
    /// Get the account nonce for a given account ID.
    pub async fn account_nonce(&self, account_id: &T::AccountId) -> Result<u64, ExtrinsicError> {
        account_nonce::get_account_nonce(&self.client, account_id)
            .await
            .map_err(|e| ExtrinsicError::AccountNonceError {
                block_hash: self.client.block_ref().hash().into(),
                account_id: account_id.clone().encode().into(),
                reason: e,
            })
    }

    /// Creates a signable transaction. This can then be signed and submitted.
    pub async fn create_signable<'call, Call>(
        &self,
        call: &'call Call,
        account_id: &T::AccountId,
        mut params: <T::TransactionExtensions as TransactionExtensions<T>>::Params,
    ) -> Result<SignableTransaction<'call, T, Client, Call>, ExtrinsicError>
    where
        Call: Payload,
    {
        self.inject_account_nonce_and_block(account_id, &mut params)
            .await?;
        self.create_signable_offline(call, params)
    }

    /// Creates a signable V4 transaction, without submitting it. This can then be signed and submitted.
    ///
    /// Prefer [`Self::create_signable()`] if you don't know which version to create; this will pick the
    /// most suitable one for the given chain.
    pub async fn create_v4_signable<'call, Call>(
        &self,
        call: &'call Call,
        account_id: &T::AccountId,
        mut params: <T::TransactionExtensions as TransactionExtensions<T>>::Params,
    ) -> Result<SignableTransaction<'call, T, Client, Call>, ExtrinsicError>
    where
        Call: Payload,
    {
        self.inject_account_nonce_and_block(account_id, &mut params)
            .await?;
        self.create_v4_signable_offline(call, params)
    }

    /// Creates a signable V5 transaction, without submitting it. This can then be signed and submitted.
    ///
    /// Prefer [`Self::create_signable()`] if you don't know which version to create; this will pick the
    /// most suitable one for the given chain.
    pub async fn create_v5_signable<'call, Call>(
        &self,
        call: &'call Call,
        account_id: &T::AccountId,
        mut params: <T::TransactionExtensions as TransactionExtensions<T>>::Params,
    ) -> Result<SignableTransaction<'call, T, Client, Call>, ExtrinsicError>
    where
        Call: Payload,
    {
        self.inject_account_nonce_and_block(account_id, &mut params)
            .await?;
        self.create_v5_signable_offline(call, params)
    }

    /// Creates a signed transaction, without submitting it.
    pub async fn create_signed<Call, S>(
        &mut self,
        call: &Call,
        signer: &S,
        params: <T::TransactionExtensions as TransactionExtensions<T>>::Params,
    ) -> Result<SubmittableTransaction<T, Client>, ExtrinsicError>
    where
        Call: Payload,
        S: Signer<T>,
    {
        let mut signable = self
            .create_signable(call, &signer.account_id(), params)
            .await?;

        signable.sign(signer)
    }

    /// Creates and signs an transaction and submits it to the chain. Passes default parameters
    /// to construct the "signed extra" and "additional" payloads needed by the transaction.
    ///
    /// Returns a [`TransactionProgress`], which can be used to track the status of the transaction
    /// and obtain details about it, once it has made it into a block.
    pub async fn sign_and_submit_then_watch_default<Call, S>(
        &mut self,
        call: &Call,
        signer: &S,
    ) -> Result<TransactionProgress<T, Client>, ExtrinsicError>
    where
        Call: Payload,
        S: Signer<T>,
        <T::TransactionExtensions as TransactionExtensions<T>>::Params: DefaultParams,
    {
        self.sign_and_submit_then_watch(call, signer, DefaultParams::default_params())
            .await
    }

    /// Creates and signs an transaction and submits it to the chain.
    ///
    /// Returns a [`TransactionProgress`], which can be used to track the status of the transaction
    /// and obtain details about it, once it has made it into a block.
    pub async fn sign_and_submit_then_watch<Call, S>(
        &mut self,
        call: &Call,
        signer: &S,
        params: <T::TransactionExtensions as TransactionExtensions<T>>::Params,
    ) -> Result<TransactionProgress<T, Client>, ExtrinsicError>
    where
        Call: Payload,
        S: Signer<T>,
    {
        self.create_signed(call, signer, params)
            .await?
            .submit_and_watch()
            .await
    }

    /// Creates and signs an transaction and submits to the chain for block inclusion. Passes
    /// default parameters to construct the "signed extra" and "additional" payloads needed
    /// by the transaction.
    ///
    /// Returns `Ok` with the transaction hash if it is valid transaction.
    ///
    /// # Note
    ///
    /// Success does not mean the transaction has been included in the block, just that it is valid
    /// and has been included in the transaction pool.
    pub async fn sign_and_submit_default<Call, S>(
        &mut self,
        call: &Call,
        signer: &S,
    ) -> Result<HashFor<T>, ExtrinsicError>
    where
        Call: Payload,
        S: Signer<T>,
        <T::TransactionExtensions as TransactionExtensions<T>>::Params: DefaultParams,
    {
        self.sign_and_submit(call, signer, DefaultParams::default_params())
            .await
    }

    /// Creates and signs an transaction and submits to the chain for block inclusion.
    ///
    /// Returns `Ok` with the transaction hash if it is valid transaction.
    ///
    /// # Note
    ///
    /// Success does not mean the transaction has been included in the block, just that it is valid
    /// and has been included in the transaction pool.
    pub async fn sign_and_submit<Call, S>(
        &mut self,
        call: &Call,
        signer: &S,
        params: <T::TransactionExtensions as TransactionExtensions<T>>::Params,
    ) -> Result<HashFor<T>, ExtrinsicError>
    where
        Call: Payload,
        S: Signer<T>,
    {
        self.create_signed(call, signer, params)
            .await?
            .submit()
            .await
    }

    /// Fetch the block header and account nonce from the current block and use
    /// them to refine our [`TransactionExtensions::Params`].
    async fn inject_account_nonce_and_block(
        &self,
        account_id: &T::AccountId,
        params: &mut <T::TransactionExtensions as TransactionExtensions<T>>::Params,
    ) -> Result<(), ExtrinsicError> {
        let block_number = self.client.block_number();
        let block_hash = self.client.block_ref().hash();
        let account_nonce = self.account_nonce(account_id).await?;

        params.inject_account_nonce(account_nonce);
        params.inject_block(block_number, block_hash);

        Ok(())
    }
}

/// The transaction versions supported by Subxt.
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
#[repr(u8)]
pub enum SupportedTransactionVersion {
    /// v4 transactions (signed and unsigned transactions)
    V4 = 4u8,
    /// v5 transactions (bare and general transactions)
    V5 = 5u8,
}

/// This is a transaction that requires signing before it can be submitted.
pub struct SignableTransaction<'call, T: Config, Client, Call> {
    client: Client,
    call: &'call Call,
    tx_extensions: <T as Config>::TransactionExtensions,
    // For V4 transactions this doesn't exist, and for V5 it does.
    tx_extension_version: Option<u8>,
}

impl<'call, T: Config, Client: OfflineClientAtBlockT<T>, Call: Payload>
    SignableTransaction<'call, T, Client, Call>
{
    /// Return the signer payload for this transaction. These are the bytes that must
    /// be signed in order to produce a valid signature for the transaction.
    pub fn signer_payload(&self) -> Result<Vec<u8>, ExtrinsicError> {
        let signer_payload = if let Some(transaction_extension_version) = self.tx_extension_version
        {
            frame_decode::extrinsics::encode_v5_signer_payload(
                self.call.pallet_name(),
                self.call.call_name(),
                self.call.call_data(),
                transaction_extension_version,
                &self.tx_extensions,
                self.client.metadata_ref(),
                self.client.metadata_ref().types(),
            )?
            .to_vec()
        } else {
            frame_decode::extrinsics::encode_v4_signer_payload(
                self.call.pallet_name(),
                self.call.call_name(),
                self.call.call_data(),
                &self.tx_extensions,
                self.client.metadata_ref(),
                self.client.metadata_ref().types(),
            )?
        };

        Ok(signer_payload)
    }

    /// Convert this [`SignableTransaction`] into a [`SubmittableTransaction`], ready to submit.
    /// The provided `signer` is responsible for providing the "from" address for the transaction,
    /// as well as providing a signature to attach to it.
    pub fn sign<S: Signer<T>>(
        &mut self,
        signer: &S,
    ) -> Result<SubmittableTransaction<T, Client>, ExtrinsicError> {
        // Given our signer, we can sign the payload representing this extrinsic.
        let signature = signer.sign(&self.signer_payload()?);
        // Now, use the signature and "from" account to build the extrinsic.
        self.sign_with_account_and_signature(&signer.account_id(), &signature)
    }

    /// Convert this [`SignableTransaction`] into a [`SubmittableTransaction`], ready to submit.
    /// An address, and something representing a signature that can be SCALE encoded, are both
    /// needed in order to construct it. If you have a `Signer` to hand, you can use
    /// [`SignableTransaction::sign()`] instead.
    pub fn sign_with_account_and_signature(
        &mut self,
        account_id: &T::AccountId,
        signature: &T::Signature,
    ) -> Result<SubmittableTransaction<T, Client>, ExtrinsicError> {
        let encoded = if let Some(transaction_extension_version) = self.tx_extension_version {
            // Pass account and signature to extensions to be added.
            self.tx_extensions.inject_signature(account_id, signature);

            frame_decode::extrinsics::encode_v5_general(
                self.call.pallet_name(),
                self.call.call_name(),
                self.call.call_data(),
                transaction_extension_version,
                &self.tx_extensions,
                self.client.metadata_ref(),
                self.client.metadata_ref().types(),
            )
        } else {
            // We need an Address, not an AccountId, to create a tx.
            let address: T::Address = account_id.clone().into();

            frame_decode::extrinsics::encode_v4_signed(
                self.call.pallet_name(),
                self.call.call_name(),
                self.call.call_data(),
                &self.tx_extensions,
                &address,
                &signature,
                self.client.metadata_ref(),
                self.client.metadata_ref().types(),
            )
        }?;

        Ok(SubmittableTransaction {
            client: self.client.clone(),
            encoded,
            marker: PhantomData,
        })
    }
}

/// This is a transaction that is ready to submit.
#[derive(Debug, Clone)]
pub struct SubmittableTransaction<T, Client> {
    client: Client,
    encoded: Vec<u8>,
    marker: PhantomData<T>,
}

impl<T, Client> SubmittableTransaction<T, Client>
where
    T: Config,
    Client: OfflineClientAtBlockT<T>,
{
    /// Calculate and return the hash of the transaction, based on the configured hasher.
    pub fn hash(&self) -> HashFor<T> {
        self.client.hasher().hash(&self.encoded)
    }

    /// Returns the SCALE encoded transaction bytes.
    pub fn encoded(&self) -> &[u8] {
        &self.encoded
    }

    /// Consumes [`SubmittableTransaction`] and returns the SCALE encoded
    /// transaction bytes.
    pub fn into_encoded(self) -> Vec<u8> {
        self.encoded.clone()
    }
}

impl<T: Config, Client: OnlineClientAtBlockT<T>> SubmittableTransaction<T, Client> {
    /// Submits the transaction to the chain.
    ///
    /// Returns a [`TransactionProgress`], which can be used to track the status of the transaction
    /// and obtain details about it, once it has made it into a block.
    pub async fn submit_and_watch(&self) -> Result<TransactionProgress<T, Client>, ExtrinsicError> {
        // Get a hash of the transaction (we'll need this later).
        let ext_hash = self.hash();

        // Submit and watch for transaction progress.
        let sub = self
            .client
            .backend()
            .submit_transaction(self.encoded())
            .await
            .map_err(ExtrinsicError::ErrorSubmittingTransaction)?;

        Ok(TransactionProgress::new(sub, self.client.clone(), ext_hash))
    }

    /// Submits the transaction to the chain for block inclusion.
    ///
    /// It's usually better to call `submit_and_watch` to get an idea of the progress of the
    /// submission and whether it's eventually successful or not. This call does not guarantee
    /// success, and is just sending the transaction to the chain.
    pub async fn submit(&self) -> Result<HashFor<T>, ExtrinsicError> {
        let ext_hash = self.hash();
        let mut sub = self
            .client
            .backend()
            .submit_transaction(self.encoded())
            .await
            .map_err(ExtrinsicError::ErrorSubmittingTransaction)?;

        // If we get a bad status or error back straight away then error, else return the hash.
        match sub.next().await {
            Some(Ok(status)) => match status {
                BackendTransactionStatus::Validated
                | BackendTransactionStatus::Broadcasted
                | BackendTransactionStatus::InBestBlock { .. }
                | BackendTransactionStatus::NoLongerInBestBlock
                | BackendTransactionStatus::InFinalizedBlock { .. } => Ok(ext_hash),
                BackendTransactionStatus::Error { message } => Err(
                    ExtrinsicError::TransactionStatusError(TransactionStatusError::Error(message)),
                ),
                BackendTransactionStatus::Invalid { message } => {
                    Err(ExtrinsicError::TransactionStatusError(
                        TransactionStatusError::Invalid(message),
                    ))
                }
                BackendTransactionStatus::Dropped { message } => {
                    Err(ExtrinsicError::TransactionStatusError(
                        TransactionStatusError::Dropped(message),
                    ))
                }
            },
            Some(Err(e)) => Err(ExtrinsicError::TransactionStatusStreamError(e)),
            None => Err(ExtrinsicError::UnexpectedEndOfTransactionStatusStream),
        }
    }

    /// Validate a transaction by submitting it to the relevant Runtime API. A transaction that is
    /// valid can be added to a block, but may still end up in an error state.
    ///
    /// Returns `Ok` with a [`ValidationResult`], which is the result of attempting to dry run the transaction.
    pub async fn validate(&self) -> Result<ValidationResult, ExtrinsicError> {
        let block_hash = self.client.block_ref().hash();

        // Approach taken from https://github.com/paritytech/json-rpc-interface-spec/issues/55.
        let mut params = Vec::with_capacity(8 + self.encoded().len() + 8);
        2u8.encode_to(&mut params);
        params.extend(self.encoded().iter());
        block_hash.encode_to(&mut params);

        let res: Vec<u8> = self
            .client
            .backend()
            .call(
                "TaggedTransactionQueue_validate_transaction",
                Some(&params),
                block_hash,
            )
            .await
            .map_err(ExtrinsicError::CannotGetValidationInfo)?;

        ValidationResult::try_from_bytes(res)
    }

    /// This returns an estimate for what the transaction is expected to cost to execute, less any tips,
    /// based on the block at which you are submitting the transaction. The actual amount paid can vary
    /// from block to block based on node traffic and other factors.
    pub async fn partial_fee_estimate(&self) -> Result<u128, ExtrinsicError> {
        let block_hash = self.client.block_ref().hash();

        // Params for the Runtime API call
        let mut params = self.encoded().to_vec();
        (self.encoded().len() as u32).encode_to(&mut params);

        // destructuring RuntimeDispatchInfo, see type information <https://paritytech.github.io/substrate/master/pallet_transaction_payment_rpc_runtime_api/struct.RuntimeDispatchInfo.html>
        // data layout: {weight_ref_time: Compact<u64>, weight_proof_size: Compact<u64>, class: u8, partial_fee: u128}
        let response = self
            .client
            .backend()
            .call(
                "TransactionPaymentApi_query_info",
                Some(&params),
                block_hash,
            )
            .await
            .map_err(ExtrinsicError::CannotGetFeeInfo)?;

        let (_, _, _, partial_fee) =
            <(Compact<u64>, Compact<u64>, u8, u128)>::decode(&mut &*response)
                .map_err(ExtrinsicError::CannotDecodeFeeInfo)?;

        Ok(partial_fee)
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use crate::client::{OfflineClient, OfflineClientAtBlock};
    use crate::config::SubstrateConfig;
    use crate::config::substrate::SpecVersionForRange;
    use crate::metadata::Metadata;
    use assert_matches::assert_matches;
    use scale_value::Value;
    use std::sync::Arc;

    fn test_client_with_metadata(metadata_bytes: &[u8]) -> OfflineClientAtBlock<SubstrateConfig> {
        test_client_with_metadata_and_genesis(metadata_bytes, None)
    }

    fn test_client_with_metadata_and_genesis(
        metadata_bytes: &[u8],
        genesis_hash: Option<crate::utils::H256>,
    ) -> OfflineClientAtBlock<SubstrateConfig> {
        let metadata = Metadata::decode(&mut &*metadata_bytes).unwrap();

        let mut builder = SubstrateConfig::builder()
            .set_metadata_for_spec_versions([(0, Arc::new(metadata))])
            .set_spec_version_for_block_ranges([SpecVersionForRange {
                block_range: 0..u64::MAX,
                spec_version: 0,
                transaction_version: 0,
            }]);

        if let Some(hash) = genesis_hash {
            builder = builder.set_genesis_hash(hash);
        }

        OfflineClient::new_with_config(builder.build())
            .at_block(0u64)
            .unwrap()
    }

    fn test_client() -> OfflineClientAtBlock<SubstrateConfig> {
        test_client_with_metadata(include_bytes!(
            "../../artifacts/polkadot_metadata_small.scale"
        ))
    }

    #[test]
    fn from_call_data_bytes_roundtrips() {
        let client = test_client();
        let tx = client.tx();

        // A call whose arguments include a variant and a compact encoded number:
        let dest = Value::unnamed_variant("Id", [Value::from_bytes([7u8; 32])]);
        let original = dynamic(
            "Balances",
            "transfer_keep_alive",
            (dest, 12_345_000_000u128),
        );

        let call_data = tx.call_data(&original).unwrap();
        let recovered = tx.from_call_data_bytes(&call_data).unwrap();

        assert_eq!(recovered.pallet_name(), "Balances");
        assert_eq!(recovered.call_name(), "transfer_keep_alive");

        // Re-encoding the recovered payload should give back identical bytes:
        assert_eq!(tx.call_data(&recovered).unwrap(), call_data);
    }

    #[test]
    fn from_call_data_bytes_decodes_call_without_arguments() {
        let client = test_client_with_metadata(include_bytes!(
            "../../artifacts/polkadot_metadata_full.scale"
        ));
        let tx = client.tx();

        let pallet = client
            .metadata_ref()
            .pallet_by_name("Sudo")
            .expect("the test metadata should contain the Sudo pallet");
        let call = pallet
            .call_variant_by_name("remove_key")
            .expect("the test metadata should contain Sudo.remove_key");
        assert!(call.fields.is_empty());

        let call_data = [pallet.call_index(), call.index];

        let recovered = tx.from_call_data_bytes(&call_data).unwrap();

        assert_eq!(recovered.pallet_name(), "Sudo");
        assert_eq!(recovered.call_name(), "remove_key");
        assert_eq!(recovered.call_data(), &Composite::Unnamed(Vec::new()));
        assert_eq!(tx.call_data(&recovered).unwrap(), call_data);
    }

    #[test]
    fn from_call_data_bytes_decodes_known_scale_fixture() {
        let client = test_client();
        let tx = client.tx();

        // System pallet index 0, remark call index 0, followed by a SCALE encoded
        // Vec containing the three bytes 1, 2 and 3
        let call_data = [0x00, 0x00, 0x0c, 0x01, 0x02, 0x03];

        let recovered = tx.from_call_data_bytes(&call_data).unwrap();

        assert_eq!(recovered.pallet_name(), "System");
        assert_eq!(recovered.call_name(), "remark");
        assert_eq!(
            recovered.call_data(),
            &Composite::Named(vec![("remark".to_owned(), Value::from_bytes([1u8, 2, 3]),)])
        );
        assert_eq!(tx.call_data(&recovered).unwrap(), call_data);
    }

    #[test]
    fn from_call_data_bytes_rejects_invalid_bytes() {
        let client = test_client();
        let tx = client.tx();

        // Not enough bytes to read the pallet and call index:
        assert_matches!(
            tx.from_call_data_bytes(&[]),
            Err(ExtrinsicError::CallDataTooShort(0))
        );
        assert_matches!(
            tx.from_call_data_bytes(&[0]),
            Err(ExtrinsicError::CallDataTooShort(1))
        );

        // A pallet index that doesn't exist:
        let unused_pallet_index = (0..=u8::MAX)
            .find(|i| client.metadata_ref().pallet_by_call_index(*i).is_none())
            .unwrap();
        assert_matches!(
            tx.from_call_data_bytes(&[unused_pallet_index, 0]),
            Err(ExtrinsicError::CannotDecodeCallData(_))
        );

        // A call index that doesn't exist in the pallet:
        let system_pallet_index = client
            .metadata_ref()
            .pallet_by_name("System")
            .unwrap()
            .call_index();
        assert_matches!(
            tx.from_call_data_bytes(&[system_pallet_index, 0xEE]),
            Err(ExtrinsicError::CannotDecodeCallData(_))
        );

        let valid = tx
            .call_data(&dynamic("System", "remark", (vec![1u8, 2, 3],)))
            .unwrap();

        // Truncated argument bytes:
        assert_matches!(
            tx.from_call_data_bytes(&valid[..valid.len() - 1]),
            Err(ExtrinsicError::CannotDecodeCallDataFields(_))
        );

        // Bytes left over after the arguments were decoded:
        let mut extended = valid.clone();
        extended.push(0);
        assert_matches!(
            tx.from_call_data_bytes(&extended),
            Err(ExtrinsicError::LeftoverBytesDecodingCallData(1))
        );
    }

    #[test]
    fn v5_signer_payload_succeeds() {
        let client = test_client_with_metadata_and_genesis(
            include_bytes!("../../artifacts/polkadot_metadata_small.scale"),
            Some(crate::utils::H256::zero()),
        );
        let tx = client.tx();

        let call = dynamic("System", "remark", (vec![1u8, 2, 3],));
        let params = crate::config::DefaultExtrinsicParamsBuilder::<SubstrateConfig>::new().build();

        let signable = tx.create_v5_signable_offline(&call, params);

        // V5 might not be supported by this metadata; if so, skip.
        let signable = match signable {
            Ok(s) => s,
            Err(ExtrinsicError::UnsupportedVersion) => return,
            Err(e) => panic!("unexpected error creating signable: {e}"),
        };

        // The signer payload should succeed and return a 32-byte blake2-256 hash.
        let payload = signable.signer_payload().unwrap();
        assert_eq!(payload.len(), 32);
    }
}