subxt_core/utils/
mod.rs

1// Copyright 2019-2024 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 account_id;
8mod account_id20;
9pub mod bits;
10mod era;
11mod multi_address;
12mod multi_signature;
13mod static_type;
14mod unchecked_extrinsic;
15mod wrapper_opaque;
16
17use alloc::borrow::ToOwned;
18use alloc::format;
19use alloc::string::String;
20use alloc::vec::Vec;
21use codec::{Compact, Decode, Encode};
22use derive_where::derive_where;
23
24pub use account_id::AccountId32;
25pub use account_id20::AccountId20;
26pub use era::Era;
27pub use multi_address::MultiAddress;
28pub use multi_signature::MultiSignature;
29pub use primitive_types::{H160, H256, H512};
30pub use static_type::Static;
31pub use unchecked_extrinsic::UncheckedExtrinsic;
32pub use wrapper_opaque::WrapperKeepOpaque;
33
34/// Wraps an already encoded byte vector, prevents being encoded as a raw byte vector as part of
35/// the transaction payload
36#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd)]
37pub struct Encoded(pub Vec<u8>);
38
39impl codec::Encode for Encoded {
40    fn encode(&self) -> Vec<u8> {
41        self.0.to_owned()
42    }
43}
44
45/// Decodes a compact encoded value from the beginning of the provided bytes,
46/// returning the value and any remaining bytes.
47pub fn strip_compact_prefix(bytes: &[u8]) -> Result<(u64, &[u8]), codec::Error> {
48    let cursor = &mut &*bytes;
49    let val = <Compact<u64>>::decode(cursor)?;
50    Ok((val.0, *cursor))
51}
52
53/// A version of [`core::marker::PhantomData`] that is also Send and Sync (which is fine
54/// because regardless of the generic param, it is always possible to Send + Sync this
55/// 0 size type).
56#[derive(Encode, Decode, scale_info::TypeInfo)]
57#[derive_where(Clone, PartialEq, Debug, Eq, Default, Hash)]
58#[scale_info(skip_type_params(T))]
59#[doc(hidden)]
60pub struct PhantomDataSendSync<T>(core::marker::PhantomData<T>);
61
62impl<T> PhantomDataSendSync<T> {
63    pub fn new() -> Self {
64        Self(core::marker::PhantomData)
65    }
66}
67
68unsafe impl<T> Send for PhantomDataSendSync<T> {}
69unsafe impl<T> Sync for PhantomDataSendSync<T> {}
70
71/// This represents a key-value collection and is SCALE compatible
72/// with collections like BTreeMap. This has the same type params
73/// as `BTreeMap` which allows us to easily swap the two during codegen.
74pub type KeyedVec<K, V> = Vec<(K, V)>;
75
76/// A unit marker struct.
77pub struct Yes;
78
79/// A quick helper to encode some bytes to hex.
80pub fn to_hex(bytes: impl AsRef<[u8]>) -> String {
81    format!("0x{}", hex::encode(bytes.as_ref()))
82}