subxt_core/
dynamic.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//! This module provides the entry points to create dynamic
6//! transactions, storage and constant lookups.
7
8use crate::metadata::{DecodeWithMetadata, Metadata};
9use alloc::vec::Vec;
10use scale_decode::DecodeAsType;
11pub use scale_value::{At, Value};
12
13/// A [`scale_value::Value`] type endowed with contextual information
14/// regarding what type was used to decode each part of it. This implements
15/// [`crate::metadata::DecodeWithMetadata`], and is used as a return type
16/// for dynamic requests.
17pub type DecodedValue = scale_value::Value<u32>;
18
19// Submit dynamic transactions.
20pub use crate::tx::payload::dynamic as tx;
21
22// Lookup constants dynamically.
23pub use crate::constants::address::dynamic as constant;
24
25// Lookup storage values dynamically.
26pub use crate::storage::address::dynamic as storage;
27
28// Execute runtime API function call dynamically.
29pub use crate::runtime_api::payload::dynamic as runtime_api_call;
30
31/// This is the result of making a dynamic request to a node. From this,
32/// we can return the raw SCALE bytes that we were handed back, or we can
33/// complete the decoding of the bytes into a [`DecodedValue`] type.
34pub struct DecodedValueThunk {
35    type_id: u32,
36    metadata: Metadata,
37    scale_bytes: Vec<u8>,
38}
39
40impl DecodeWithMetadata for DecodedValueThunk {
41    fn decode_with_metadata(
42        bytes: &mut &[u8],
43        type_id: u32,
44        metadata: &Metadata,
45    ) -> Result<Self, scale_decode::Error> {
46        let mut v = Vec::with_capacity(bytes.len());
47        v.extend_from_slice(bytes);
48        *bytes = &[];
49        Ok(DecodedValueThunk {
50            type_id,
51            metadata: metadata.clone(),
52            scale_bytes: v,
53        })
54    }
55}
56
57impl DecodedValueThunk {
58    /// Return the SCALE encoded bytes handed back from the node.
59    pub fn into_encoded(self) -> Vec<u8> {
60        self.scale_bytes
61    }
62    /// Return the SCALE encoded bytes handed back from the node without taking ownership of them.
63    pub fn encoded(&self) -> &[u8] {
64        &self.scale_bytes
65    }
66    /// Decode the SCALE encoded storage entry into a dynamic [`DecodedValue`] type.
67    pub fn to_value(&self) -> Result<DecodedValue, scale_decode::Error> {
68        let val = scale_value::scale::decode_as_type(
69            &mut &*self.scale_bytes,
70            self.type_id,
71            self.metadata.types(),
72        )?;
73        Ok(val)
74    }
75    /// decode the `DecodedValueThunk` into a concrete type.
76    pub fn as_type<T: DecodeAsType>(&self) -> Result<T, scale_decode::Error> {
77        T::decode_as_type(
78            &mut &self.scale_bytes[..],
79            self.type_id,
80            self.metadata.types(),
81        )
82    }
83}