subxt 0.50.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
mod block_number_or_ref;
mod blocks;

use super::ClientAtBlock;
use super::OfflineClientAtBlockT;
use crate::backend::{Backend, BlockRef};
use crate::config::{Config, HashFor, Hasher, Header};
use crate::error::OnlineClientError;
use crate::error::{BlocksError, OnlineClientAtBlockError};
use crate::metadata::{ArcMetadata, Metadata};
use crate::transactions::TransactionsClient;
use codec::{Compact, Decode, Encode};
use core::marker::PhantomData;
use frame_decode::helpers::ToTypeRegistry;
use frame_metadata::{RuntimeMetadata, RuntimeMetadataPrefixed};
use scale_info_legacy::TypeRegistrySet;
use std::sync::Arc;

pub use block_number_or_ref::BlockNumberOrRef;
pub use blocks::{Block, Blocks};

/// A client which requires a connection to a chain, and allows interacting with it.
#[derive(Clone, Debug)]
pub struct OnlineClient<T: Config> {
    inner: Arc<OnlineClientInner<T>>,
}

struct OnlineClientInner<T: Config> {
    /// The configuration for this client.
    config: T,
    /// Chain genesis hash. Needed to construct transactions,
    /// so we obtain it up front on constructing this.
    genesis_hash: HashFor<T>,
    /// The RPC methods used to communicate with the node.
    backend: Arc<dyn Backend<T>>,
}

impl<T: Config> std::fmt::Debug for OnlineClientInner<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("OnlineClientInner")
            .field("config", &"<config>")
            .field("backend", &"Arc<backend impl>")
            .finish()
    }
}

impl<T: Config> OnlineClient<T> {
    /// Construct a new [`OnlineClient`] using default configuration which
    /// connects to a locally running node on `ws://127.0.0.1:9944`.
    #[cfg(all(feature = "jsonrpsee", feature = "runtime"))]
    pub async fn new() -> Result<OnlineClient<T>, OnlineClientError>
    where
        T: Default,
    {
        OnlineClient::new_with_config(Default::default()).await
    }

    /// Construct a new [`OnlineClient`] using the provided configuration which
    /// connects to a local running node on `ws://127.0.0.1:9944`.
    #[cfg(all(feature = "jsonrpsee", feature = "runtime"))]
    pub async fn new_with_config(config: T) -> Result<OnlineClient<T>, OnlineClientError> {
        let url = "ws://127.0.0.1:9944";
        OnlineClient::from_url_with_config(config, url).await
    }

    /// Construct a new [`OnlineClient`] using default configuration and
    /// connecting to the given URL.
    #[cfg(all(feature = "jsonrpsee", feature = "runtime"))]
    pub async fn from_url(url: impl AsRef<str>) -> Result<OnlineClient<T>, OnlineClientError>
    where
        T: Default,
    {
        OnlineClient::from_url_with_config(Default::default(), url).await
    }

    /// Construct a new [`OnlineClient`] using the provided configuration and
    /// connecting to the given URL.
    #[cfg(all(feature = "jsonrpsee", feature = "runtime"))]
    pub async fn from_url_with_config(
        config: T,
        url: impl AsRef<str>,
    ) -> Result<OnlineClient<T>, OnlineClientError> {
        let url_str = url.as_ref();
        if !subxt_rpcs::utils::url_is_secure(url_str).map_err(OnlineClientError::RpcError)? {
            return Err(OnlineClientError::RpcError(subxt_rpcs::Error::InsecureUrl(
                url_str.to_string(),
            )));
        }
        OnlineClient::from_insecure_url_with_config(config, url).await
    }

    /// Construct a new [`OnlineClient`] using default configuration and
    /// connecting to the given URL.
    ///
    /// Allows insecure URLs without SSL encryption, e.g. (http:// and ws:// URLs).
    #[cfg(all(feature = "jsonrpsee", feature = "runtime"))]
    pub async fn from_insecure_url(
        url: impl AsRef<str>,
    ) -> Result<OnlineClient<T>, OnlineClientError>
    where
        T: Default,
    {
        OnlineClient::from_insecure_url_with_config(Default::default(), url).await
    }

    /// Construct a new [`OnlineClient`] using the provided configuration and
    /// connecting to the given URL.
    ///
    /// Allows insecure URLs without SSL encryption, e.g. (http:// and ws:// URLs).
    #[cfg(all(feature = "jsonrpsee", feature = "runtime"))]
    pub async fn from_insecure_url_with_config(
        config: T,
        url: impl AsRef<str>,
    ) -> Result<OnlineClient<T>, OnlineClientError> {
        let rpc_client = subxt_rpcs::RpcClient::from_insecure_url(url).await?;
        OnlineClient::from_rpc_client_with_config(config, rpc_client).await
    }

    /// Construct a new [`OnlineClient`] by providing a [`subxt_rpcs::RpcClient`] to drive the connection.
    /// This will use the current default [`Backend`], which may change in future releases.
    #[cfg(all(feature = "jsonrpsee", feature = "runtime"))]
    pub async fn from_rpc_client(
        rpc_client: impl Into<subxt_rpcs::RpcClient>,
    ) -> Result<OnlineClient<T>, OnlineClientError>
    where
        T: Default,
    {
        OnlineClient::from_rpc_client_with_config(Default::default(), rpc_client).await
    }

    /// Construct a new [`OnlineClient`] by providing a [`subxt_rpcs::RpcClient`] to drive the connection,
    /// and chain configuration. This will use the current default [`Backend`], which may change in future
    /// releases.
    #[cfg(all(feature = "jsonrpsee", feature = "runtime"))]
    pub async fn from_rpc_client_with_config(
        config: T,
        rpc_client: impl Into<subxt_rpcs::RpcClient>,
    ) -> Result<OnlineClient<T>, OnlineClientError> {
        let rpc_client = rpc_client.into();
        let backend = crate::backend::CombinedBackend::builder()
            .build_with_background_driver(rpc_client)
            .await
            .map_err(OnlineClientError::CannotBuildCombinedBackend)?;
        OnlineClient::from_backend_with_config(config, Arc::new(backend)).await
    }

    /// Construct a new [`OnlineClient`] by providing an underlying [`Backend`]
    /// implementation to power it and using default configuration.
    pub async fn from_backend<B: Backend<T>>(
        backend: Arc<B>,
    ) -> Result<OnlineClient<T>, OnlineClientError>
    where
        T: Default,
    {
        OnlineClient::from_backend_with_config(Default::default(), backend).await
    }

    /// Construct a new [`OnlineClient`] by providing an underlying [`Backend`]
    /// implementation to power it and some chain configuration.
    pub async fn from_backend_with_config<B: Backend<T>>(
        config: T,
        backend: Arc<B>,
    ) -> Result<OnlineClient<T>, OnlineClientError> {
        let genesis_hash = match config.genesis_hash() {
            Some(hash) => hash,
            None => backend
                .genesis_hash()
                .await
                .map_err(OnlineClientError::CannotGetGenesisHash)?,
        };

        Ok(OnlineClient {
            inner: Arc::new(OnlineClientInner {
                config,
                genesis_hash,
                backend,
            }),
        })
    }

    /// Return the genesis hash of the connected chain.
    pub fn genesis_hash(&self) -> HashFor<T> {
        self.inner.genesis_hash
    }

    /// Construct, sign and submit transactions. This is an alias for `self.at_current_block().await?.transactions()`.
    pub async fn transactions(
        &self,
    ) -> Result<TransactionsClient<T, OnlineClientAtBlockImpl<T>>, OnlineClientAtBlockError> {
        let at_block = self.at_current_block().await?;
        Ok(at_block.transactions())
    }

    /// Construct, sign and submit transactions. This is an alias for `self.transactions()`.
    pub async fn tx(
        &self,
    ) -> Result<TransactionsClient<T, OnlineClientAtBlockImpl<T>>, OnlineClientAtBlockError> {
        self.transactions().await
    }

    /// Obtain a stream of all blocks imported by the node.
    ///
    /// **Note:** You probably want to use [`Self::stream_blocks()`] most of
    /// the time. Blocks returned here may be pruned at any time and become inaccessible,
    /// leading to errors when trying to work with them.
    pub async fn stream_all_blocks(&self) -> Result<Blocks<T>, BlocksError> {
        // We need a hasher to know how to hash things. Thus, we need metadata to instantiate
        // the hasher, so let's use the current block.
        let current_block = self
            .at_current_block()
            .await
            .map_err(BlocksError::CannotGetCurrentBlock)?;
        let hasher = current_block.client.hasher.clone();

        let stream = self
            .inner
            .backend
            .stream_all_block_headers(hasher)
            .await
            .map_err(BlocksError::CannotGetBlockHeaderStream)?;

        Ok(Blocks::from_headers_stream(self.clone(), stream))
    }

    /// Obtain a stream of blocks imported by the node onto the current best fork.
    ///
    /// **Note:** You probably want to use [`Self::stream_blocks()`] most of
    /// the time. Blocks returned here may be pruned at any time and become inaccessible,
    /// leading to errors when trying to work with them.
    pub async fn stream_best_blocks(&self) -> Result<Blocks<T>, BlocksError> {
        // We need a hasher to know how to hash things. Thus, we need metadata to instantiate
        // the hasher, so let's use the current block.
        let current_block = self
            .at_current_block()
            .await
            .map_err(BlocksError::CannotGetCurrentBlock)?;
        let hasher = current_block.client.hasher.clone();

        let stream = self
            .inner
            .backend
            .stream_best_block_headers(hasher)
            .await
            .map_err(BlocksError::CannotGetBlockHeaderStream)?;

        Ok(Blocks::from_headers_stream(self.clone(), stream))
    }

    /// Obtain a stream of finalized blocks.
    pub async fn stream_blocks(&self) -> Result<Blocks<T>, BlocksError> {
        // We need a hasher to know how to hash things. Thus, we need metadata to instantiate
        // the hasher, so let's use the current block.
        let current_block = self
            .at_current_block()
            .await
            .map_err(BlocksError::CannotGetCurrentBlock)?;
        let hasher = current_block.client.hasher.clone();

        let stream = self
            .inner
            .backend
            .stream_finalized_block_headers(hasher)
            .await
            .map_err(BlocksError::CannotGetBlockHeaderStream)?;

        Ok(Blocks::from_headers_stream(self.clone(), stream))
    }

    /// Instantiate a client to work at the current finalized block _at the time of instantiation_.
    /// This does not track new blocks.
    pub async fn at_current_block(
        &self,
    ) -> Result<ClientAtBlock<T, OnlineClientAtBlockImpl<T>>, OnlineClientAtBlockError> {
        let latest_block = self
            .inner
            .backend
            .latest_finalized_block_ref()
            .await
            .map_err(|e| OnlineClientAtBlockError::CannotGetCurrentBlock { reason: e })?;

        self.at_block(latest_block).await
    }

    /// Instantiate a client for working at a specific block.
    pub async fn at_block(
        &self,
        number_or_hash: impl Into<BlockNumberOrRef<T>>,
    ) -> Result<ClientAtBlock<T, OnlineClientAtBlockImpl<T>>, OnlineClientAtBlockError> {
        let number_or_hash = number_or_hash.into();

        // We are given either a block hash or number. We need both.
        let (block_ref, block_number) = match number_or_hash {
            BlockNumberOrRef::BlockRef(block_ref) => {
                let block_hash = block_ref.hash();
                let block_header = self
                    .inner
                    .backend
                    .block_header(block_hash)
                    .await
                    .map_err(|e| OnlineClientAtBlockError::CannotGetBlockHeader {
                        block_hash: block_hash.into(),
                        reason: e,
                    })?
                    .ok_or(OnlineClientAtBlockError::BlockHeaderNotFound {
                        block_hash: block_hash.into(),
                    })?;
                (block_ref, block_header.number())
            }
            BlockNumberOrRef::Number(block_number) => {
                let block_ref = self
                    .inner
                    .backend
                    .block_number_to_hash(block_number)
                    .await
                    .map_err(|e| OnlineClientAtBlockError::CannotGetBlockHash {
                        block_number,
                        reason: e,
                    })?
                    .ok_or(OnlineClientAtBlockError::BlockNotFound { block_number })?;
                (block_ref, block_number)
            }
        };

        self.at_block_hash_and_number(block_ref, block_number).await
    }

    /// Instantiate a client for working at a specific block. This takes a block hash/ref _and_ the
    /// corresponding block number. When both are available, this saves an RPC call to obtain one from
    /// the other.
    ///
    /// **Warning:** If the block hash and number do not align, then things will go wrong. Prefer to
    /// use [`Self::at_block`] if in any doubt.
    pub async fn at_block_hash_and_number(
        &self,
        block_ref: impl Into<BlockRef<HashFor<T>>>,
        block_number: u64,
    ) -> Result<ClientAtBlock<T, OnlineClientAtBlockImpl<T>>, OnlineClientAtBlockError> {
        let block_ref = block_ref.into();
        let block_hash = block_ref.hash();

        // Obtain the spec version so that we know which metadata to use at this block.
        // Obtain the transaction version because it's required for constructing extrinsics.
        let (spec_version, transaction_version) = match self
            .inner
            .config
            .spec_and_transaction_version_for_block_number(block_number)
        {
            Some(version) => version,
            None => {
                let spec_version_bytes = self
                    .inner
                    .backend
                    .call("Core_version", None, block_hash)
                    .await
                    .map_err(|e| OnlineClientAtBlockError::CannotGetSpecVersion {
                        block_hash: block_hash.into(),
                        reason: e,
                    })?;

                // This is the "modern" version information. We get this back for
                // all Polkadot RC blocks and try this first.
                #[derive(codec::Decode, Debug)]
                struct SpecVersionHeader {
                    _spec_name: String,
                    _impl_name: String,
                    _authoring_version: u32,
                    spec_version: u32,
                    _impl_version: u32,
                    _apis: Vec<([u8; 8], u32)>,
                    transaction_version: u32,
                }

                // For old Kusama RC blocks (and possibly others), the transaction
                // version field hasn't been added yet and so we default it to 0.
                #[derive(codec::Decode, Debug)]
                struct OldSpecVersionHeader {
                    _spec_name: String,
                    _impl_name: String,
                    _authoring_version: u32,
                    spec_version: u32,
                    _impl_version: u32,
                    _apis: Vec<([u8; 8], u32)>,
                }

                SpecVersionHeader::decode(&mut &spec_version_bytes[..])
                    .map(|version| (version.spec_version, version.transaction_version))
                    .or_else(|_| {
                        OldSpecVersionHeader::decode(&mut &spec_version_bytes[..])
                            .map(|version| (version.spec_version, 0))
                    })
                    .map_err(|e| OnlineClientAtBlockError::CannotDecodeSpecVersion {
                        block_hash: block_hash.into(),
                        reason: e,
                    })?
            }
        };

        // Obtain the metadata for the block. Allow our config to cache it.
        let metadata = match self.inner.config.metadata_for_spec_version(spec_version) {
            Some(metadata) => metadata,
            None => {
                let metadata: Metadata =
                    match get_metadata(&*self.inner.backend, block_hash).await? {
                        m @ RuntimeMetadata::V0(_)
                        | m @ RuntimeMetadata::V1(_)
                        | m @ RuntimeMetadata::V2(_)
                        | m @ RuntimeMetadata::V3(_)
                        | m @ RuntimeMetadata::V4(_)
                        | m @ RuntimeMetadata::V5(_)
                        | m @ RuntimeMetadata::V6(_)
                        | m @ RuntimeMetadata::V7(_) => {
                            return Err(OnlineClientAtBlockError::UnsupportedMetadataVersion {
                                block_hash: block_hash.into(),
                                version: m.version(),
                            });
                        }
                        RuntimeMetadata::V8(m) => {
                            let types = get_legacy_types(self, &m, spec_version)?;
                            Metadata::from_v8(&m, &types).map_err(|e| {
                                OnlineClientAtBlockError::CannotConvertLegacyMetadata {
                                    block_hash: block_hash.into(),
                                    metadata_version: 8,
                                    reason: e,
                                }
                            })?
                        }
                        RuntimeMetadata::V9(m) => {
                            let types = get_legacy_types(self, &m, spec_version)?;
                            Metadata::from_v9(&m, &types).map_err(|e| {
                                OnlineClientAtBlockError::CannotConvertLegacyMetadata {
                                    block_hash: block_hash.into(),
                                    metadata_version: 9,
                                    reason: e,
                                }
                            })?
                        }
                        RuntimeMetadata::V10(m) => {
                            let types = get_legacy_types(self, &m, spec_version)?;
                            Metadata::from_v10(&m, &types).map_err(|e| {
                                OnlineClientAtBlockError::CannotConvertLegacyMetadata {
                                    block_hash: block_hash.into(),
                                    metadata_version: 10,
                                    reason: e,
                                }
                            })?
                        }
                        RuntimeMetadata::V11(m) => {
                            let types = get_legacy_types(self, &m, spec_version)?;
                            Metadata::from_v11(&m, &types).map_err(|e| {
                                OnlineClientAtBlockError::CannotConvertLegacyMetadata {
                                    block_hash: block_hash.into(),
                                    metadata_version: 11,
                                    reason: e,
                                }
                            })?
                        }
                        RuntimeMetadata::V12(m) => {
                            let types = get_legacy_types(self, &m, spec_version)?;
                            Metadata::from_v12(&m, &types).map_err(|e| {
                                OnlineClientAtBlockError::CannotConvertLegacyMetadata {
                                    block_hash: block_hash.into(),
                                    metadata_version: 12,
                                    reason: e,
                                }
                            })?
                        }
                        RuntimeMetadata::V13(m) => {
                            let types = get_legacy_types(self, &m, spec_version)?;
                            Metadata::from_v13(&m, &types).map_err(|e| {
                                OnlineClientAtBlockError::CannotConvertLegacyMetadata {
                                    block_hash: block_hash.into(),
                                    metadata_version: 13,
                                    reason: e,
                                }
                            })?
                        }
                        RuntimeMetadata::V14(m) => Metadata::from_v14(m).map_err(|e| {
                            OnlineClientAtBlockError::CannotConvertModernMetadata {
                                block_hash: block_hash.into(),
                                metadata_version: 14,
                                reason: e,
                            }
                        })?,
                        RuntimeMetadata::V15(m) => Metadata::from_v15(m).map_err(|e| {
                            OnlineClientAtBlockError::CannotConvertModernMetadata {
                                block_hash: block_hash.into(),
                                metadata_version: 15,
                                reason: e,
                            }
                        })?,
                        RuntimeMetadata::V16(m) => Metadata::from_v16(m).map_err(|e| {
                            OnlineClientAtBlockError::CannotConvertModernMetadata {
                                block_hash: block_hash.into(),
                                metadata_version: 16,
                                reason: e,
                            }
                        })?,
                    };
                let metadata = Arc::new(metadata);
                self.inner
                    .config
                    .set_metadata_for_spec_version(spec_version, metadata.clone());
                metadata
            }
        };

        let online_client_at_block = OnlineClientAtBlockImpl {
            client: self.clone(),
            hasher: <T::Hasher as Hasher>::new(&metadata),
            metadata,
            block_ref,
            block_number,
            spec_version,
            transaction_version,
        };

        Ok(ClientAtBlock {
            client: online_client_at_block,
            marker: PhantomData,
        })
    }
}

/// This represents an online client at a specific block.
#[doc(hidden)]
pub trait OnlineClientAtBlockT<T: Config>: OfflineClientAtBlockT<T> {
    /// Return the RPC methods we'll use to interact with the node.
    fn backend(&self) -> &dyn Backend<T>;
    /// Return the block hash for the current block.
    fn block_ref(&self) -> &BlockRef<HashFor<T>>;
    /// Return the inner [`OnlineClient`].
    fn client(&self) -> OnlineClient<T>;
}

/// An implementation of the [`OnlineClientAtBlockImpl`] trait, which is used in conjunction
/// with [`crate::client::ClientAtBlock`] to provide a working client. You won't tend to need this
/// type and instead should prefer to refer to [`crate::client::OnlineClientAtBlock`].
#[derive(Debug, Clone)]
pub struct OnlineClientAtBlockImpl<T: Config> {
    client: OnlineClient<T>,
    metadata: ArcMetadata,
    hasher: T::Hasher,
    block_ref: BlockRef<HashFor<T>>,
    block_number: u64,
    spec_version: u32,
    transaction_version: u32,
}

impl<T: Config> OnlineClientAtBlockT<T> for OnlineClientAtBlockImpl<T> {
    fn backend(&self) -> &dyn Backend<T> {
        &*self.client.inner.backend
    }
    fn block_ref(&self) -> &BlockRef<HashFor<T>> {
        &self.block_ref
    }
    fn client(&self) -> OnlineClient<T> {
        self.client.clone()
    }
}

impl<T: Config> OfflineClientAtBlockT<T> for OnlineClientAtBlockImpl<T> {
    fn metadata_ref(&self) -> &Metadata {
        &self.metadata
    }
    fn metadata(&self) -> ArcMetadata {
        self.metadata.clone()
    }
    fn block_number(&self) -> u64 {
        self.block_number
    }
    fn genesis_hash(&self) -> Option<HashFor<T>> {
        Some(self.client.inner.genesis_hash)
    }
    fn spec_version(&self) -> u32 {
        self.spec_version
    }
    fn transaction_version(&self) -> u32 {
        self.transaction_version
    }
    fn hasher(&self) -> &T::Hasher {
        &self.hasher
    }
}

fn get_legacy_types<'a, T: Config, Md: ToTypeRegistry>(
    client: &'a OnlineClient<T>,
    metadata: &Md,
    spec_version: u32,
) -> Result<TypeRegistrySet<'a>, OnlineClientAtBlockError> {
    let mut types = client
        .inner
        .config
        .legacy_types_for_spec_version(spec_version)
        .ok_or(OnlineClientAtBlockError::MissingLegacyTypes)?;

    // Extend the types with information from the metadata (ie event/error/call enums):
    let additional_types = frame_decode::helpers::type_registry_from_metadata(metadata)
        .map_err(|e| OnlineClientAtBlockError::CannotInjectMetadataTypes { parse_error: e })?;
    types.prepend(additional_types);

    Ok(types)
}

async fn get_metadata<T: Config>(
    backend: &dyn Backend<T>,
    block_hash: HashFor<T>,
) -> Result<RuntimeMetadata, OnlineClientAtBlockError> {
    // First, try to use the "modern" metadata APIs to get the most recent version we can.
    let version_to_get = backend
        .call("Metadata_metadata_versions", None, block_hash)
        .await
        .ok()
        .and_then(|res| <Vec<u32>>::decode(&mut &res[..]).ok())
        .and_then(|versions| {
            // We want to filter out the "unstable" version, which is represented by u32::MAX.
            versions.into_iter().filter(|v| *v != u32::MAX).max()
        });

    // We had success calling the above API, so we expect the "modern" metadata API to work.
    if let Some(version_to_get) = version_to_get {
        let version_bytes = version_to_get.encode();
        let rpc_response = backend
            .call(
                "Metadata_metadata_at_version",
                Some(&version_bytes),
                block_hash,
            )
            .await
            .map_err(|e| OnlineClientAtBlockError::CannotGetMetadata {
                block_hash: block_hash.into(),
                reason: format!("Error calling Metadata_metadata_at_version: {e}"),
            })?;

        // Option because we may have asked for a version that doesn't exist. Compact because we get back a Vec<u8>
        // of the metadata bytes, and the Vec is preceded by it's compact encoded length. The actual bytes are then
        // decoded as a `RuntimeMetadataPrefixed`, after this.
        let (_, metadata) = <Option<(Compact<u32>, RuntimeMetadataPrefixed)>>::decode(&mut &rpc_response[..])
            .map_err(|e| OnlineClientAtBlockError::CannotGetMetadata {
                block_hash: block_hash.into(),
                reason: format!("Error decoding response for Metadata_metadata_at_version: {e}"),
            })?
            .ok_or_else(|| OnlineClientAtBlockError::CannotGetMetadata {
                block_hash: block_hash.into(),
                reason: format!("No metadata returned for the latest version from Metadata_metadata_versions ({version_to_get})"),
            })?;

        return Ok(metadata.1);
    }

    // We didn't get a version from Metadata_metadata_versions, so fall back to the "old" API.
    let metadata_bytes = backend
        .call("Metadata_metadata", None, block_hash)
        .await
        .map_err(|e| OnlineClientAtBlockError::CannotGetMetadata {
            block_hash: block_hash.into(),
            reason: format!("Error calling Metadata_metadata: {e}"),
        })?;

    let (_, metadata) = <(Compact<u32>, RuntimeMetadataPrefixed)>::decode(&mut &metadata_bytes[..])
        .map_err(|e| OnlineClientAtBlockError::CannotGetMetadata {
            block_hash: block_hash.into(),
            reason: format!("Error decoding response for Metadata_metadata: {e}"),
        })?;

    Ok(metadata.1)
}