subxt_core/tx/
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//! Construct and sign transactions.
6//!
7//! # Example
8//!
9//! ```rust
10//! use subxt_signer::sr25519::dev;
11//! use subxt_macro::subxt;
12//! use subxt_core::config::PolkadotConfig;
13//! use subxt_core::config::DefaultExtrinsicParamsBuilder as Params;
14//! use subxt_core::tx;
15//! use subxt_core::utils::H256;
16//! use subxt_core::metadata;
17//!
18//! // If we generate types without `subxt`, we need to point to `::subxt_core`:
19//! #[subxt(
20//!     crate = "::subxt_core",
21//!     runtime_metadata_path = "../artifacts/polkadot_metadata_small.scale",
22//! )]
23//! pub mod polkadot {}
24//!
25//! // Gather some other information about the chain that we'll need to construct valid extrinsics:
26//! let state = tx::ClientState::<PolkadotConfig> {
27//!     metadata: {
28//!         let metadata_bytes = include_bytes!("../../../artifacts/polkadot_metadata_small.scale");
29//!         metadata::decode_from(&metadata_bytes[..]).unwrap()
30//!     },
31//!     genesis_hash: {
32//!         let h = "91b171bb158e2d3848fa23a9f1c25182fb8e20313b2c1eb49219da7a70ce90c3";
33//!         let bytes = hex::decode(h).unwrap();
34//!         H256::from_slice(&bytes)
35//!     },
36//!     runtime_version: tx::RuntimeVersion {
37//!         spec_version: 9370,
38//!         transaction_version: 20,
39//!     }
40//! };
41//!
42//! // Now we can build a balance transfer extrinsic.
43//! let dest = dev::bob().public_key().into();
44//! let call = polkadot::tx().balances().transfer_allow_death(dest, 10_000);
45//! let params = Params::new().tip(1_000).nonce(0).build();
46//!
47//! // We can validate that this lines up with the given metadata:
48//! tx::validate(&call, &state.metadata).unwrap();
49//!
50//! // We can build a signed transaction:
51//! let signed_call = tx::create_v4_signed(&call, &state, params)
52//!     .unwrap()
53//!     .sign(&dev::alice());
54//!
55//! // And log it:
56//! println!("Tx: 0x{}", hex::encode(signed_call.encoded()));
57//! ```
58
59pub mod payload;
60pub mod signer;
61
62use crate::config::{Config, ExtrinsicParams, ExtrinsicParamsEncoder, Hasher};
63use crate::error::{Error, ExtrinsicError, MetadataError};
64use crate::metadata::Metadata;
65use crate::utils::Encoded;
66use alloc::borrow::{Cow, ToOwned};
67use alloc::vec::Vec;
68use codec::{Compact, Encode};
69use payload::Payload;
70use signer::Signer as SignerT;
71use sp_crypto_hashing::blake2_256;
72
73// Expose these here since we expect them in some calls below.
74pub use crate::client::{ClientState, RuntimeVersion};
75
76/// Run the validation logic against some extrinsic you'd like to submit. Returns `Ok(())`
77/// if the call is valid (or if it's not possible to check since the call has no validation hash).
78/// Return an error if the call was not valid or something went wrong trying to validate it (ie
79/// the pallet or call in question do not exist at all).
80pub fn validate<Call: Payload>(call: &Call, metadata: &Metadata) -> Result<(), Error> {
81    if let Some(details) = call.validation_details() {
82        let expected_hash = metadata
83            .pallet_by_name_err(details.pallet_name)?
84            .call_hash(details.call_name)
85            .ok_or_else(|| MetadataError::CallNameNotFound(details.call_name.to_owned()))?;
86
87        if details.hash != expected_hash {
88            return Err(MetadataError::IncompatibleCodegen.into());
89        }
90    }
91    Ok(())
92}
93
94/// Returns the suggested transaction versions to build for a given chain, or an error
95/// if Subxt doesn't support any version expected by the chain.
96///
97/// If the result is [`TransactionVersion::V4`], use the `v4` methods in this module. If it's
98/// [`TransactionVersion::V5`], use the `v5` ones.
99pub fn suggested_version(metadata: &Metadata) -> Result<TransactionVersion, Error> {
100    let versions = metadata.extrinsic().supported_versions();
101
102    if versions.contains(&4) {
103        Ok(TransactionVersion::V4)
104    } else if versions.contains(&5) {
105        Ok(TransactionVersion::V5)
106    } else {
107        Err(ExtrinsicError::UnsupportedVersion.into())
108    }
109}
110
111/// The transaction versions supported by Subxt.
112#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
113pub enum TransactionVersion {
114    /// v4 transactions (signed and unsigned transactions)
115    V4,
116    /// v5 transactions (bare and general transactions)
117    V5,
118}
119
120/// Return the SCALE encoded bytes representing the call data of the transaction.
121pub fn call_data<Call: Payload>(call: &Call, metadata: &Metadata) -> Result<Vec<u8>, Error> {
122    let mut bytes = Vec::new();
123    call.encode_call_data_to(metadata, &mut bytes)?;
124    Ok(bytes)
125}
126
127/// Creates a V4 "unsigned" transaction without submitting it.
128pub fn create_v4_unsigned<T: Config, Call: Payload>(
129    call: &Call,
130    metadata: &Metadata,
131) -> Result<Transaction<T>, Error> {
132    create_unsigned_at_version(call, 4, metadata)
133}
134
135/// Creates a V5 "bare" transaction without submitting it.
136pub fn create_v5_bare<T: Config, Call: Payload>(
137    call: &Call,
138    metadata: &Metadata,
139) -> Result<Transaction<T>, Error> {
140    create_unsigned_at_version(call, 5, metadata)
141}
142
143// Create a V4 "unsigned" transaction or V5 "bare" transaction.
144fn create_unsigned_at_version<T: Config, Call: Payload>(
145    call: &Call,
146    tx_version: u8,
147    metadata: &Metadata,
148) -> Result<Transaction<T>, Error> {
149    // 1. Validate this call against the current node metadata if the call comes
150    // with a hash allowing us to do so.
151    validate(call, metadata)?;
152
153    // 2. Encode extrinsic
154    let extrinsic = {
155        let mut encoded_inner = Vec::new();
156        // encode the transaction version first.
157        tx_version.encode_to(&mut encoded_inner);
158        // encode call data after this byte.
159        call.encode_call_data_to(metadata, &mut encoded_inner)?;
160        // now, prefix byte length:
161        let len = Compact(
162            u32::try_from(encoded_inner.len()).expect("extrinsic size expected to be <4GB"),
163        );
164        let mut encoded = Vec::new();
165        len.encode_to(&mut encoded);
166        encoded.extend(encoded_inner);
167        encoded
168    };
169
170    // Wrap in Encoded to ensure that any more "encode" calls leave it in the right state.
171    Ok(Transaction::from_bytes(extrinsic))
172}
173
174/// Construct a v4 extrinsic, ready to be signed.
175pub fn create_v4_signed<T: Config, Call: Payload>(
176    call: &Call,
177    client_state: &ClientState<T>,
178    params: <T::ExtrinsicParams as ExtrinsicParams<T>>::Params,
179) -> Result<PartialTransactionV4<T>, Error> {
180    // 1. Validate this call against the current node metadata if the call comes
181    // with a hash allowing us to do so.
182    validate(call, &client_state.metadata)?;
183
184    // 2. SCALE encode call data to bytes (pallet u8, call u8, call params).
185    let call_data = call_data(call, &client_state.metadata)?;
186
187    // 3. Construct our custom additional/extra params.
188    let additional_and_extra_params =
189        <T::ExtrinsicParams as ExtrinsicParams<T>>::new(client_state, params)?;
190
191    // Return these details, ready to construct a signed extrinsic from.
192    Ok(PartialTransactionV4 {
193        call_data,
194        additional_and_extra_params,
195    })
196}
197
198/// Construct a v5 "general" extrinsic, ready to be signed or emitted as is.
199pub fn create_v5_general<T: Config, Call: Payload>(
200    call: &Call,
201    client_state: &ClientState<T>,
202    params: <T::ExtrinsicParams as ExtrinsicParams<T>>::Params,
203) -> Result<PartialTransactionV5<T>, Error> {
204    // 1. Validate this call against the current node metadata if the call comes
205    // with a hash allowing us to do so.
206    validate(call, &client_state.metadata)?;
207
208    // 2. Work out which TX extension version to target based on metadata (unless we
209    // explicitly ask for a specific transaction version at a later step).
210    let tx_extensions_version = client_state
211        .metadata
212        .extrinsic()
213        .transaction_extensions_version();
214
215    // 3. SCALE encode call data to bytes (pallet u8, call u8, call params).
216    let call_data = call_data(call, &client_state.metadata)?;
217
218    // 4. Construct our custom additional/extra params.
219    let additional_and_extra_params =
220        <T::ExtrinsicParams as ExtrinsicParams<T>>::new(client_state, params)?;
221
222    // Return these details, ready to construct a signed extrinsic from.
223    Ok(PartialTransactionV5 {
224        call_data,
225        additional_and_extra_params,
226        tx_extensions_version,
227    })
228}
229
230/// A partially constructed V4 extrinsic, ready to be signed.
231pub struct PartialTransactionV4<T: Config> {
232    call_data: Vec<u8>,
233    additional_and_extra_params: T::ExtrinsicParams,
234}
235
236impl<T: Config> PartialTransactionV4<T> {
237    /// Return the bytes representing the call data for this partially constructed
238    /// extrinsic.
239    pub fn call_data(&self) -> &[u8] {
240        &self.call_data
241    }
242
243    // Obtain bytes representing the signer payload and run call some function
244    // with them. This can avoid an allocation in some cases.
245    fn with_signer_payload<F, R>(&self, f: F) -> R
246    where
247        F: for<'a> FnOnce(Cow<'a, [u8]>) -> R,
248    {
249        let mut bytes = self.call_data.clone();
250        self.additional_and_extra_params
251            .encode_signer_payload_value_to(&mut bytes);
252        self.additional_and_extra_params
253            .encode_implicit_to(&mut bytes);
254
255        if bytes.len() > 256 {
256            f(Cow::Borrowed(&blake2_256(&bytes)))
257        } else {
258            f(Cow::Owned(bytes))
259        }
260    }
261
262    /// Return the V4 signer payload for this extrinsic. These are the bytes that must
263    /// be signed in order to produce a valid signature for the extrinsic.
264    pub fn signer_payload(&self) -> Vec<u8> {
265        self.with_signer_payload(|bytes| bytes.to_vec())
266    }
267
268    /// Convert this [`PartialTransactionV4`] into a V4 signed [`Transaction`], ready to submit.
269    /// The provided `signer` is responsible for providing the "from" address for the transaction,
270    /// as well as providing a signature to attach to it.
271    pub fn sign<Signer>(&self, signer: &Signer) -> Transaction<T>
272    where
273        Signer: SignerT<T>,
274    {
275        // Given our signer, we can sign the payload representing this extrinsic.
276        let signature = self.with_signer_payload(|bytes| signer.sign(&bytes));
277        // Now, use the signature and "from" address to build the extrinsic.
278        self.sign_with_account_and_signature(signer.account_id(), &signature)
279    }
280
281    /// Convert this [`PartialTransactionV4`] into a V4 signed [`Transaction`], ready to submit.
282    /// The provided `address` and `signature` will be used.
283    pub fn sign_with_account_and_signature(
284        &self,
285        account_id: T::AccountId,
286        signature: &T::Signature,
287    ) -> Transaction<T> {
288        let extrinsic = {
289            let mut encoded_inner = Vec::new();
290            // "is signed" + transaction protocol version (4)
291            (0b10000000 + 4u8).encode_to(&mut encoded_inner);
292            // from address for signature
293            let address: T::Address = account_id.into();
294            address.encode_to(&mut encoded_inner);
295            // the signature
296            signature.encode_to(&mut encoded_inner);
297            // attach custom extra params
298            self.additional_and_extra_params
299                .encode_value_to(&mut encoded_inner);
300            // and now, call data (remembering that it's been encoded already and just needs appending)
301            encoded_inner.extend(&self.call_data);
302            // now, prefix byte length:
303            let len = Compact(
304                u32::try_from(encoded_inner.len()).expect("extrinsic size expected to be <4GB"),
305            );
306            let mut encoded = Vec::new();
307            len.encode_to(&mut encoded);
308            encoded.extend(encoded_inner);
309            encoded
310        };
311
312        // Return an extrinsic ready to be submitted.
313        Transaction::from_bytes(extrinsic)
314    }
315}
316
317/// A partially constructed V5 general extrinsic, ready to be signed or emitted as-is.
318pub struct PartialTransactionV5<T: Config> {
319    call_data: Vec<u8>,
320    additional_and_extra_params: T::ExtrinsicParams,
321    tx_extensions_version: u8,
322}
323
324impl<T: Config> PartialTransactionV5<T> {
325    /// Return the bytes representing the call data for this partially constructed
326    /// extrinsic.
327    pub fn call_data(&self) -> &[u8] {
328        &self.call_data
329    }
330
331    /// Return the V5 signer payload for this extrinsic. These are the bytes that must
332    /// be signed in order to produce a valid signature for the extrinsic.
333    pub fn signer_payload(&self) -> [u8; 32] {
334        let mut bytes = self.call_data.clone();
335
336        self.additional_and_extra_params
337            .encode_signer_payload_value_to(&mut bytes);
338        self.additional_and_extra_params
339            .encode_implicit_to(&mut bytes);
340
341        blake2_256(&bytes)
342    }
343
344    /// Convert this [`PartialTransactionV5`] into a V5 "general" [`Transaction`].
345    ///
346    /// This transaction has not been explicitly signed. Use [`Self::sign`]
347    /// or [`Self::sign_with_account_and_signature`] if you wish to provide a
348    /// signature (this is usually a necessary step).
349    pub fn to_transaction(&self) -> Transaction<T> {
350        let extrinsic = {
351            let mut encoded_inner = Vec::new();
352            // "is general" + transaction protocol version (5)
353            (0b01000000 + 5u8).encode_to(&mut encoded_inner);
354            // Encode versions for the transaction extensions
355            self.tx_extensions_version.encode_to(&mut encoded_inner);
356            // Encode the actual transaction extensions values
357            self.additional_and_extra_params
358                .encode_value_to(&mut encoded_inner);
359            // and now, call data (remembering that it's been encoded already and just needs appending)
360            encoded_inner.extend(&self.call_data);
361            // now, prefix byte length:
362            let len = Compact(
363                u32::try_from(encoded_inner.len()).expect("extrinsic size expected to be <4GB"),
364            );
365            let mut encoded = Vec::new();
366            len.encode_to(&mut encoded);
367            encoded.extend(encoded_inner);
368            encoded
369        };
370
371        // Return an extrinsic ready to be submitted.
372        Transaction::from_bytes(extrinsic)
373    }
374
375    /// Convert this [`PartialTransactionV5`] into a V5 "general" [`Transaction`] with a signature.
376    ///
377    /// Signing the transaction injects the signature into the transaction extension data, which is why
378    /// this method borrows self mutably. Signing repeatedly will override the previous signature.
379    pub fn sign<Signer>(&mut self, signer: &Signer) -> Transaction<T>
380    where
381        Signer: SignerT<T>,
382    {
383        // Given our signer, we can sign the payload representing this extrinsic.
384        let signature = signer.sign(&self.signer_payload());
385        // Now, use the signature and "from" account to build the extrinsic.
386        self.sign_with_account_and_signature(&signer.account_id(), &signature)
387    }
388
389    /// Convert this [`PartialTransactionV5`] into a V5 "general" [`Transaction`] with a signature.
390    /// Prefer [`Self::sign`] if you have a [`SignerT`] instance to use.
391    ///
392    /// Signing the transaction injects the signature into the transaction extension data, which is why
393    /// this method borrows self mutably. Signing repeatedly will override the previous signature.
394    pub fn sign_with_account_and_signature(
395        &mut self,
396        account_id: &T::AccountId,
397        signature: &T::Signature,
398    ) -> Transaction<T> {
399        // Inject the signature into the transaction extensions
400        // before constructing it.
401        self.additional_and_extra_params
402            .inject_signature(account_id, signature);
403
404        self.to_transaction()
405    }
406}
407
408/// This represents a signed transaction that's ready to be submitted.
409/// Use [`Transaction::encoded()`] or [`Transaction::into_encoded()`] to
410/// get the bytes for it, or [`Transaction::hash()`] to get the hash.
411pub struct Transaction<T> {
412    encoded: Encoded,
413    marker: core::marker::PhantomData<T>,
414}
415
416impl<T: Config> Transaction<T> {
417    /// Create a [`Transaction`] from some already-signed and prepared
418    /// extrinsic bytes,
419    pub fn from_bytes(tx_bytes: Vec<u8>) -> Self {
420        Self {
421            encoded: Encoded(tx_bytes),
422            marker: core::marker::PhantomData,
423        }
424    }
425
426    /// Calculate and return the hash of the extrinsic, based on the configured hasher.
427    pub fn hash(&self) -> T::Hash {
428        T::Hasher::hash_of(&self.encoded)
429    }
430
431    /// Returns the SCALE encoded extrinsic bytes.
432    pub fn encoded(&self) -> &[u8] {
433        &self.encoded.0
434    }
435
436    /// Consumes this [`Transaction`] and returns the SCALE encoded
437    /// extrinsic bytes.
438    pub fn into_encoded(self) -> Vec<u8> {
439        self.encoded.0
440    }
441}