Skip to main content

subxt/
utils.rs

1// Copyright 2019-2026 Parity Technologies (UK) Ltd.
2// This file is dual-licensed as Apache-2.0 or GPL-3.0.
3// see LICENSE for license details.
4
5//! Miscellaneous utility helpers.
6
7mod era;
8#[cfg(feature = "jsonrpsee")]
9mod fetch_chain_spec;
10mod multi_address;
11mod multi_signature;
12mod range_map;
13mod static_type;
14mod unchecked_extrinsic;
15mod wrapper_opaque;
16mod yesnomaybe;
17
18pub mod bits;
19pub mod eth;
20
21use codec::{Compact, Decode, Encode};
22use derive_where::derive_where;
23
24pub use era::Era;
25pub use multi_address::MultiAddress;
26pub use multi_signature::MultiSignature;
27pub use primitive_types::{H160, H256, H512};
28pub use range_map::{RangeMap, RangeMapBuilder, RangeMapError};
29pub use static_type::Static;
30pub use unchecked_extrinsic::UncheckedExtrinsic;
31pub use wrapper_opaque::WrapperKeepOpaque;
32pub use yesnomaybe::{Maybe, No, NoMaybe, Yes, YesMaybe, YesNo};
33
34pub use subxt_utils_accountid32::AccountId32;
35
36// Lightclient helper to fetch chain spec from a running node.
37#[cfg(feature = "jsonrpsee")]
38pub use fetch_chain_spec::{FetchChainspecError, fetch_chainspec_from_rpc_node};
39
40/// Wraps an already encoded byte vector, prevents being encoded as a raw byte vector as part of
41/// the transaction payload
42#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd)]
43pub struct Encoded(pub Vec<u8>);
44
45impl codec::Encode for Encoded {
46    fn encode(&self) -> Vec<u8> {
47        self.0.to_owned()
48    }
49}
50
51/// Decodes a compact encoded value from the beginning of the provided bytes,
52/// returning the value and any remaining bytes.
53pub fn strip_compact_prefix(bytes: &[u8]) -> Result<(u64, &[u8]), codec::Error> {
54    let cursor = &mut &*bytes;
55    let val = <Compact<u64>>::decode(cursor)?;
56    Ok((val.0, *cursor))
57}
58
59/// A version of [`core::marker::PhantomData`] that is also Send and Sync (which is fine
60/// because regardless of the generic param, it is always possible to Send + Sync this
61/// 0 size type).
62#[derive(Encode, Decode, scale_info::TypeInfo)]
63#[derive_where(Clone, PartialEq, Debug, Eq, Default, Hash)]
64#[scale_info(skip_type_params(T))]
65#[doc(hidden)]
66pub struct PhantomDataSendSync<T>(core::marker::PhantomData<T>);
67
68impl<T> PhantomDataSendSync<T> {
69    pub fn new() -> Self {
70        Self(core::marker::PhantomData)
71    }
72}
73
74unsafe impl<T> Send for PhantomDataSendSync<T> {}
75unsafe impl<T> Sync for PhantomDataSendSync<T> {}
76
77/// This represents a key-value collection and is SCALE compatible
78/// with collections like BTreeMap. This has the same type params
79/// as `BTreeMap` which allows us to easily swap the two during codegen.
80pub type KeyedVec<K, V> = Vec<(K, V)>;
81
82/// A quick helper to encode some bytes to hex.
83pub fn to_hex(bytes: impl AsRef<[u8]>) -> String {
84    format!("0x{}", hex::encode(bytes.as_ref()))
85}