Skip to content

Releases: paritytech/subxt

v0.33.0

07 Dec 11:11
v0.33.0
f06a95d
Compare
Choose a tag to compare

[0.33.0] - 2023-12-06

This release makes a bunch of small QoL improvements and changes. Let's look at the main ones.

Add support for configuring multiple chains (#1238)

The light client support previously provided a high level interface for connecting to single chains (ie relay chains). This PR exposes a "low level" interface which allows smoldot (the light client implementation we use) to be configured somewhat more arbitrarily, and then converted into a valid subxt OnlineClient to be used.

See this example for more on how to do this.

We'll likely refine this over time and add a slightly higher level interface to make common operations much easier to do.

Support decoding signed extensions (#1209 and #1235)

This PR makes it possible to decode the signed extensions in extrinsics. This looks something like:

let api = OnlineClient::<PolkadotConfig>::new().await?;

// Get blocks; here we just subscribe to them:
let mut blocks_sub = api.blocks().subscribe_finalized().await?;

while let Some(block) = blocks_sub.next().await {
    let block = block?;

    // Fetch the extrinsics in the block:
    let extrinsics = block.extrinsics().await?;

    // Iterate over them:
    for extrinsic in extrinsics.iter() {

        // Returns None if the extrinsic isn't signed, so no signed extensions:
        let Some(signed_exts) = extrinsic.signed_extensions() else {
            continue;
        };

        // We can ask for a couple of common values, None if not found:
        println!("Tip: {:?}", signed_exts.tip());
        println!("Nonce: {:?}", signed_exts.tip());

        // Or we can find and decode into a static signed extension type
        // (Err if we hit a decode error first, then None if it's not found):
        if let Ok(Some(era)) = signed_exts.find::<CheckMortality<PolkadotConfig>>() {
            println!("Era: {era:?}");
        }

        // Or we can iterate over the signed extensions to work with them:
        for signed_ext in signed_exts {
            println!("Signed Extension name: {}", signed_ext.name());

            // We can try to statically decode each one:
            if let Ok(Some(era)) = signed_ext.as_signed_extension::<CheckMortality<PolkadotConfig>>() {
                println!("Era: {era:?}");
            }

            // Or we can dynamically decode it into a `scale_value::Value`:
            if let Ok(value) = signed_ext.value() {
                println!("Decoded extension: {value}");
            }
        }
    }
}

See the API docs for more.

ChargeAssetTxPayment: Add support for generic AssetId

Still on the topic of signed extensions, the ChargeAssetTxPayment extension was previously not able to be used with a generic AssetId, which prohibited it from being used on the Asset Hub (which uses a MultiLocation instead). To address this, we added an AssetId type to our subxt::Config, which can now be configured.

One example of doing that can be found here.

This example uses a generated MultiLocation type to be used as the AssetId. Currently it requires a rather hideous set of manual clones like so:

#[subxt::subxt(
    runtime_metadata_path = "../artifacts/polkadot_metadata_full.scale",
    derive_for_type(path = "xcm::v2::multilocation::MultiLocation", derive = "Clone"),
    derive_for_type(path = "xcm::v2::multilocation::Junctions", derive = "Clone"),
    derive_for_type(path = "xcm::v2::junction::Junction", derive = "Clone"),
    derive_for_type(path = "xcm::v2::NetworkId", derive = "Clone"),
    derive_for_type(path = "xcm::v2::BodyId", derive = "Clone"),
    derive_for_type(path = "xcm::v2::BodyPart", derive = "Clone"),
    derive_for_type(
        path = "bounded_collections::weak_bounded_vec::WeakBoundedVec",
        derive = "Clone"
    )
)]

This is something we plan to address in the next version of Subxt.

Change SignedExtension matching logic (#1283)

Before this release, each signed extension had a unique name (SignedExtension::NAME). We'd use this name to figure out which signed extensions to apply for a given chain inside the signed_extensions::AnyOf type.

However, we recently ran into a new signed extension in Substrate called SkipCheckIfFeeless. This extension would wrap another signed extension, but maintained its own name. It has since been "hidden" from the public Substrate interface again, but a result of encountering this is that we have generalised the way that we "match" on signed extensions, so that we can be smarter about it going forwards.

So now, for a given signed extension, we go from:

impl<T: Config> SignedExtension<T> for ChargeAssetTxPayment<T> {
    const NAME: &'static str = "ChargeAssetTxPayment";
    type Decoded = Self;
}

To:

impl<T: Config> SignedExtension<T> for ChargeAssetTxPayment<T> {
    type Decoded = Self;
    fn matches(identifier: &str, type_id: u32, types: &PortableRegistry) -> bool {
        identifier == "ChargeAssetTxPayment"
    }
}

On the whole, we continue matching by name, as in the example above, but this allows an author to inspect the type of the signed extension (and subtypes of it) too if they want the signed extension to match (and thus be used) only in certain cases.

Remove wait_for_in_block helper method (#1237)

One can no longer use tx.wait_for_in_block to wait for a transaction to enter a block. The reason for this removal is that, especially when we migrate to the new chainHead APIs, we will no longer be able to reliably obtain any details about the block that the transaction made it into.

In other words, the following sort of thing would often fail:

tx.wait_for_in_block()
  .await?
  .wait_for_success()
  .await?;

The reason for this is that the block announced in the transaction status may not have been "pinned" yet in the new APIs. In the old APIs, errors would occasionally be encountered because the block announced may have been pruned by the time we ask for details for it. Overall; having an "unreliable" higher level API felt like a potential foot gun.

That said, you can still achieve the same via the lower level APIs like so:

while let Some(status) = tx.next().await {
    match status? {
        TxStatus::InBestBlock(tx_in_block) | TxStatus::InFinalizedBlock(tx_in_block) => {
            // now, we can attempt to work with the block, eg:
            tx_in_block.wait_for_success().await?;
        },
        TxStatus::Error { message } | TxStatus::Invalid { message } | TxStatus::Dropped { message } => {
            // Handle any errors:
            println!("Error submitting tx: {message}");
        },
        // Continue otherwise:
        _ => continue,
    }
}

Subxt-codegen: Tidy crate interface (#1225)

The subxt-codegen crate has always been a bit of a mess because it wasn't really supposed to be used outside of the subxt crates, which had led to issues like #1211.

This PR tidies up the interface to that crate so that it's much easier now to programmatically generate the Subxt interface. Now, we have three properly supported ways to do this, depending on your needs:

  1. Using the #[subxt] macro.
  2. Using the subxt codegen CLI command.
  3. Programmatically via the subxt-codegen crate.

Each method aims to expose a similar and consistent set of options.

If you were previously looking to use parts of the type generation logic to, for instance, generate runtime types but not the rest of the Subxt interface, then the https://github.com/paritytech/scale-typegen crate will aim to fill this role eventually.

That sums up the most significant changes. A summary of all of the relevant changes is as follows:

Added

  • CLI: Add command to fetch chainSpec and optimize its size (#1278)
  • Add legacy RPC usage example (#1279)
  • impl RpcClientT for Arc<T> and Box<T> (#1277)
  • RPC: Implement legacy RPC system_account_next_index (#1250)
  • Lightclient: Add support for configuring multiple chains (#1238)
  • Extrinsics: Allow static decoding of signed extensions (#1235)
  • Extrinsics: Support decoding signed extensions (#1209)
  • ChargeAssetTxPayment: Add support for generic AssetId (eg u32 or MultiLocation) (#1227)
  • Add Clone + Debug on Payloads/Addresses, and compare child storage results (#1203)

Changed

  • Lightclient: Update smoldot to 0.14.0 and smoldot-light to 0.12.0 (#1307)
  • Cargo: Switch to workspace lints (#1299)
  • Update substrate-* and signer-related dependencies (#1297)
  • Change SignedExtension matching logic and remove SkipCheckIfFeeless bits (#1283)
  • Update the README with the new location ...
Read more

v0.31.0

02 Aug 14:47
v0.31.0
059723e
Compare
Choose a tag to compare

[0.31.0] - 2023-08-02

This is a small release whose primary goal is to bump the versions of scale-encode, scale-decode and scale-value being used, to benefit from recent changes in those crates.

scale-decode changes how compact values are decoded as part of #1103. A compact encoded struct should now be properly decoded into a struct of matching shape (which implements DecodeAsType). This will hopefully resolve issues around structs like Perbill. When decoding the SCALE bytes for such types into scale_value::Value, the Value will now be a composite type wrapping a value, and not just the value.

We've also figured out how to sign extrinsics using browser wallets when a Subxt app is compiled to WASM; see #1067 for more on that!

The key commits:

Added

  • Add browser extension signing example (#1067)

Changed

  • Bump to latest scale-encode/decode/value and fix test running (#1103)
  • Set minimum supported rust-version to 1.70 (#1097)

Fixed

  • Tests: support 'substrate-node' too and allow multiple binary paths (#1102)

v0.30.0

24 Jul 16:53
v0.30.0
44b1690
Compare
Choose a tag to compare

[0.30.0] - 2023-07-24

This release beings with it a number of exciting additions. Let's cover a few of the most significant ones:

Light client support (unstable)

This release adds support for light clients using Smoldot, both when compiling native binaries and when compiling to WASM to run in a browser environment. This is unstable for now while we continue testing it and work on making use of the new RPC APIs.

Here's how to use it:

use subxt::{
    client::{LightClient, LightClientBuilder},
    PolkadotConfig
};
use subxt_signer::sr25519::dev;

// Create a light client:
let api = LightClient::<PolkadotConfig>::builder()
    // You can also pass a chain spec directly using `build`, which is preferred:
    .build_from_url("ws://127.0.0.1:9944")
    .await?;

// Working with the interface is then the same as before:
let dest = dev::bob().public_key().into();
let balance_transfer_tx = polkadot::tx().balances().transfer(dest, 10_000);
let events = api
    .tx()
    .sign_and_submit_then_watch_default(&balance_transfer_tx, &dev::alice())
    .await?
    .wait_for_finalized_success()
    .await?;

At the moment you may encounter certain things that don't work; please file an issue if you do!

V15 Metadata

This release stabilizes the metadata V15 interface, which brings a few changes but primarily allows you to interact with Runtime APIs via an ergonomic Subxt interface:

// We can use the static interface to interact in a type safe way:
#[subxt::subxt(runtime_metadata_path = "path/to/metadata.scale")]
pub mod polkadot {}

let runtime_call = polkadot::apis()
    .metadata()
    .metadata_versions();

// Or we can use the dynamic interface like so:
use subxt::dynamic::Value;

let runtime_call = subxt::dynamic::runtime_api_call(
    "Metadata",
    "metadata_versions",
    Vec::<Value<()>>::new()
);

This is no longer behind a feature flag, but if the chain you're connecting to doesn't use V15 metadata yet then the above will be unavailable.

subxt-signer

The new subxt-signer crate provides the ability to sign transactions using either sr25519 or ECDSA. It's WASM compatible, and brings in fewer dependencies than using sp_core/sp_keyring does, while having an easy to use interface. Here's an example of signing a transaction using it:

use subxt::{OnlineClient, PolkadotConfig};
use subxt_signer::sr25519::dev;

let api = OnlineClient::<PolkadotConfig>::new().await?;

// Build the extrinsic; a transfer to bob:
let dest = dev::bob().public_key().into();
let balance_transfer_tx = polkadot::tx().balances().transfer(dest, 10_000);

// Sign and submit the balance transfer extrinsic from Alice:
let from = dev::alice();
let events = api
    .tx()
    .sign_and_submit_then_watch_default(&balance_transfer_tx, &from)
    .await?
    .wait_for_finalized_success()
    .await?;

Dev keys should only be used for tests since they are publicly known. Actual keys can be generated from URIs, phrases or raw entropy, and derived using soft/hard junctions:

use subxt_signer::{ SecretUri, sr25519::Keypair };
use std::str::FromStr;

// From a phrase (see `bip39` crate on generating phrases):
let phrase = bip39::Mnemonic::parse(phrase).unwrap();
let keypair = Keypair::from_phrase(&phrase, Some("Password")).unwrap();

// Or from a URI:
let uri = SecretUri::from_str("//Alice").unwrap();
let keypair = Keypair::from_uri(&uri).unwrap();

// Deriving a new key from an existing one:
let keypair = keypair.derive([
    DeriveJunction::hard("Alice"),
    DeriveJunction::soft("stash")
]);

Breaking changes

A few small breaking changes have occurred:

  • There is no longer a need for an Index associated type in your Config implementations; we now work it out dynamically where needed.
  • The "substrate-compat" feature flag is no longer enabled by default. subxt-signer added native signing support and can be used instead of bringing in Substrate dependencies to sign transactions now. You can still enable this feature flag as before to make use of them if needed.
    • Note: Be aware that Substrate crates haven't been published in a while and have fallen out of date, though. This will be addressed eventually, and when it is we can bring the Substrate crates back uptodate here.

For anything else that crops up, the compile errors and API docs will hopefully point you in the right direction, but please raise an issue if not.

For a full list of changes, see below:

Added

  • Example: How to connect to parachain (#1043)
  • ECDSA Support in signer (#1064)
  • Add subxt_signer crate for native & WASM compatible signing (#1016)
  • Add light client platform WASM compatible (#1026)
  • light-client: Add experimental light-client support (#965)
  • Add diff command to CLI tool to visualize metadata changes (#1015)
  • CLI: Allow output to be written to file (#1018)

Changed

  • Remove substrate-compat default feature flag (#1078)
  • runtime API: Substitute UncheckedExtrinsic with custom encoding (#1076)
  • Remove Index type from Config trait (#1074)
  • Utilize Metadata V15 (#1041)
  • chain_getBlock extrinsics encoding (#1024)
  • Make tx payload details public (#1014)
  • CLI tool tests (#977)
  • Support NonZero numbers (#1012)
  • Get account nonce via state_call (#1002)
  • add #[allow(rustdoc::broken_intra_doc_links)] to subxt-codegen (#998)

Fixed

  • remove parens in hex output for CLI tool (#1017)
  • Prevent bugs when reusing type ids in hashing (#1075)
  • Fix invalid generation of types with >1 generic parameters (#1023)
  • Fix jsonrpsee web features (#1025)
  • Fix codegen validation when Runtime APIs are stripped (#1000)
  • Fix hyperlink (#994)
  • Remove invalid redundant clone warning (#996)

v0.29.0

01 Jun 13:34
v0.29.0
e40a862
Compare
Choose a tag to compare

[0.29.0] - 2023-06-01

This is another big release for Subxt with a bunch of awesome changes. Let's talk about some of the notable ones:

A new guide

This release will come with overhauled documentation and examples which is much more comprehensive than before, and goes into much more detail on each of the main areas that Subxt can work in.

Check out the documentation for more. We'll continue to build on this with some larger examples, too, going forwards. (#968) is particularly cool as it's our first example showcasing Subxt working with Yew and WASM; it'll be extended with more documentation and things in the next release.

A more powerful CLI tool: an explore command.

The CLI tool has grown a new command, explore. Point it at a node and use explore to get information about the calls, constants and storage of a node, with a helpful interface that allows you to progressively dig into each of these areas!

Support for (unstable) V15 metadata and generating a Runtime API interface

One of the biggest changes in this version is that, given (unstable) V15 metadata, Subxt can now generate a nice interface to make working with Runtime APIs as easy as building extrinsics or storage queries. This is currently unstable until the V15 metadata format is stabilised, and so will break as we introduce more tweaks to the metadata format. We hope to stabilise V15 metadata soon; see this for more information. At this point, we'll stabilize support in Subxt.

Support for decoding extrinsics

Up until now, you were able to retrieve the bytes for extrinsics, but weren't able to use Subxt to do much with those bytes.

Now, we expose several methods to decode extrinsics that work much like decoding events:

#[subxt::subxt(runtime_metadata_path = "polkadot_metadata.scale")]
pub mod polkadot {}

// Get some block:
let block = api.blocks().at_latest().await?;

// Find and decode a specific extrinsic in the block:
let remark = block.find::<polkadot::system::calls::Remark>()?;

// Iterate the extrinsics in the block:
for ext in block.iter() {
    // Decode a specific extrinsic into the call data:
    let remark = ext.as_extrinsic::<polkadot::system::calls::Remark>()?;
    // Decode any extrinsic into an enum containing the call data:
    let extrinsic = ext.as_root_extrinsic::<polkadot::Call>()?;
}

New Metadata Type (#974)

Previously, the subxt_metadata crate was simply a collection of functions that worked directly on frame_metadata types. Then, in subxt, we had a custom metadata type which wrapped this to provide the interface needed by various Subxt internals and traits.

Now, the subxt_metadata crate exposes our own Metadata type which can be decoded from the same wire format as the frame_metadata types we used to use. This type is now used throughout Subxt, as well as in the codegen stuff, and provides a single unified interface for working with metadata that is independent of the actual underlying metadata version we're using.

This shouldn't lead to breakages in most code, but if you need to load metadata for an OfflineClient you might previously have done this:

use subxt::ext::frame_metadata::RuntimeMetadataPrefixed;
use subxt::metadata::Metadata;

let metadata = RuntimeMetadataPrefixed::decode(&mut &*bytes).unwrap();
let metadata = Metadata::try_from(metadata).unwrap();

But now you'd do this:

use subxt::metadata::Metadata;

let metadata = Metadata::decode(&mut &*bytes).unwrap();

Otherwise, if you implement traits like TxPayload directly, you'll need to tweak the implementations to use the new Metadata type, which exposes everything you used to be able to get hold of but behind a slightly different interface.

Removing as_pallet_event method (#953)

In an effort to simplify the number of ways we have to decode events, as_pallet_event was removed. You can achieve a similar thing by calling as_root_event, which will decode any event that the static interface knows about into an outer enum of pallet names to event names. if you only care about a specific event, you can match on this enum to look for events from a specific pallet.

Another reason that as_pallet_event was removed was that it could potentially decode events from the wrong pallets into what you're looking for, if the event shapes happened to line up, which was a potential foot gun.

Added as_root_error for decoding errors.

Much like we can call as_root_extrinsic or as_root_event to decode extrinsics and events into a top level enum, we've also added as_root_error to do the same for errors and help to make this interface consistent across the board.

Beyond these, there's a bunch more that's been added, fixed and changes. A full list of the notable changes in this release are as follows:

Added

  • Add topics to EventDetails (#989)
  • Yew Subxt WASM examples (#968)
  • CLI subxt explore commands (#950)
  • Retain specific runtime APIs (#961)
  • Subxt Guide (#890)
  • Partial fee estimates for SubmittableExtrinsic (#910)
  • Add ability to opt out from default derives and attributes (#925)
  • add no_default_substitutions to the macro and cli (#936)
  • extrinsics: Decode extrinsics from blocks (#929)
  • Metadata V15: Generate Runtime APIs (#918) and (#947)
  • impl Header and Hasher for some substrate types behind the "substrate-compat" feature flag (#934)
  • add as_root_error for helping to decode ModuleErrors (#930)

Changed

  • Update scale-encode, scale-decode and scale-value to latest (#991)
  • restrict sign_with_address_and_signature interface (#988)
  • Introduce Metadata type (#974) and (#978)
  • Have a pass over metadata validation (#959)
  • remove as_pallet_extrinsic and as_pallet_event (#953)
  • speed up ui tests. (#944)
  • cli: Use WS by default instead of HTTP (#954)
  • Upgrade to syn 2.0 (#875)
  • Move all deps to workspace toml (#932)
  • Speed up CI (#928) and (#926)
  • metadata: Use v15 internally (#912)
  • Factor substrate node runner into separate crate (#913)
  • Remove need to import parity-scale-codec to use subxt macro (#907)

Fixed

  • use blake2 for extrinsic hashing (#921)
  • Ensure unique types in codegen (#967)
  • use unit type in polkadot config (#943)

v0.28.0

12 Apr 10:08
v0.28.0
2a4da61
Compare
Choose a tag to compare

[0.28.0] - 2022-04-11

This is a fairly significant change; what follows is a description of the main changes to be aware of:

Unify how we encode and decode static and dynamic types (#842)

Prior to this, static types generated by codegen (ie subxt macro) would implement Encode and Decode from the parity-scale-codec library. This meant that they woule be encoded-to and decoded-from based on their shape. Dynamic types (eg the subxt::dynamic::Value type) would be encoded and decoded based on the node metadata instead.

This change makes use of the new scale-encode and scale-decode crates to auto-implement EncodeAsType and DecodeAsType on all of our static types. These traits allow types to take the node metadata into account when working out how best to encode and decode into them. By using metadata, we can be much more flexible/robust about how to encode/decode various types (as an example, nested transactions will now be portable across runtimes). Additionally, we can merge our codepaths for static and dynamic encoding/decoding, since both static and dynamic types can implement these traits. Read the PR description for more info.

A notable impact of this is that any types you wish to substitute when performing codegen (via the CLI tool or #[subxt] macro) must also implement EncodeAsType and DecodeAsType too. Substrate types, for instance, generally do not. To work around this, #886 introduces a Static type and enhances the type substitution logic so that you're able to wrap any types which only implement Encode and Decode to work (note that you lose out on the improvements from EncodeAsType and DecodeAsType when you do this):

#[subxt::subxt(
    runtime_metadata_path = "/path/to/metadata.scale",
    substitute_type(
        type = "sp_runtime::multiaddress::MultiAddress<A, B>",
        with = "::subxt::utils::Static<::sp_runtime::multiaddress::MultiAddress<A, B>>"
    )
)]
pub mod node_runtime {}

So, if you want to substitute in Substrate types, wrap them in ::subxt::utils::Static in the type substitution, as above. #886 also generally improves type substitution so that you can substitute the generic params in nested types, since it's required in the above.

Several types have been renamed as a result of this unification (though they aren't commonly made explicit use of). Additionally, to obtain the bytes from a storage address, instead of doing:

let addr_bytes = storage_address.to_bytes()

You must now do:

let addr_bytes = cxt.client().storage().address_bytes(&storage_address).unwrap();

This is because the address on it's own no longer requires as much static information, and relies more heavily now on the node metadata to encode it to bytes.

Expose Signer payload (#861)

This is not a breaking change, but notable in that is adds create_partial_signed_with_nonce and create_partial_signed to the TxClient to allow you to break extrinsic creation into two steps:

  1. building a payload, and then
  2. when a signature is provided, getting back an extrinsic ready to be submitted.

This allows a signer payload to be obtained from Subxt, handed off to some external application, and then once a signature has been obtained, that can be passed back to Subxt to complete the creation of an extrinsic. This opens the door to using browser wallet extensions, for instance, to sign Subxt payloads.

Stripping unneeded pallets from metadata (#879)

This is not a breaking change, but adds the ability to use the Subxt CLI tool to strip out all but some named list of pallets from a metadata bundle. Aside from allowing you to store a significantly smaller metadata bundle with only the APIs you need in it, it will also lead to faster codegen, since there's much less of it to do.

Use a command like subxt metadata --pallets Balances,System to select specific pallets. You can provide an existing metadata file to take that and strip it, outputting a smaller bundle. Alternately it will grab the metadata from a local node and strip that before outputting.

Dispatch error changes (#878)

The DispatchError returned from either attempting to submit an extrinsic, or from calling .dry_run() has changed. It's now far more complete with respect to the information it returns in each case, and the interface has been tidied up. Changes include:

  • For ModuleError's, instead of err.pallet and err.error, you can obtain error details using let details = err.details()? and then details.pallet() and details.error().
  • DryRunResult is now a custom enum with 3 states, Success, DispatchError or TransactionValidityError. The middle of these contains much more information than previously.
  • Errors in general have been marked #[non_exahustive] since they could grow and change at any time. (Owing to our use of scale-decode internally, we are not so contrained when it comes to having precise variant indexes or anything now, and can potentially deprecate rather than remove old variants as needed).
  • On a lower level, the rpc.dry_run() RPC call now returns the raw dry run bytes which can then be decoded with the help of metadata into our DryRunResult.

Extrinsic submission changes (#897)

It was found by @furoxr that Substrate nodes will stop sending transaction progress events under more circumstances than we originally expected. Thus, now calls like wait_for_finalized() and wait_for_in_block() will stop waiting for events when any of the following is sent from the node:

  • Usurped
  • Finalized
  • FinalityTimeout
  • Invalid
  • Dropped

Previously we'd only close the subscription and stop waiting when we saw a Finalized or FinalityTimeout event. Thanks for digging into this @furoxr!

Add at_latest() method (#900 and #904)

A small breaking change; previously we had .at(None) or .at(Some(block_hash)) methods in a few places to obtain things at either the latest block or some specific block hash.

This API has been clarified; we now have .at_latest() to obtain the thing at the latest block, or .at(block_hash) (note; no more option) to obtain the thing at some fixed block hash. In a few instances this has allowed us to ditch the async from the .at() call.

That covers the larger changes in this release. For more details, have a look at all of the notable PRs since the last release here:

Added

  • added at_latest (#900 and #904)
  • Metadata: Retain a subset of metadata pallets (#879)
  • Expose signer payload to allow external signing (#861)
  • Add ink! as a user of subxt (#837)
  • codegen: Add codegen error (#841)
  • codegen: allow documentation to be opted out of (#843)
  • re-export sp_core and sp_runtime (#853)
  • Allow generating only runtime types in subxt macro (#845)
  • Add 'Static' type and improve type substitution codegen to accept it (#886)

Changed

  • Improve Dispatch Errors (#878)
  • Use scale-encode and scale-decode to encode and decode based on metadata (#842)
  • For smoldot: support deserializing block number in header from hex or number (#863)
  • Bump Substrate dependencies to latest (#905)

Fixed

  • wait_for_finalized behavior if the tx dropped, usurped or invalid (#897)

v0.27.1

15 Feb 18:32
v0.27.1
6d3c377
Compare
Choose a tag to compare

[0.27.1] - 2022-02-15

Added

  • Add find_last for block types (#825)

v0.27.0

13 Feb 16:35
v0.27.0
7b0e06c
Compare
Choose a tag to compare

[0.27.0] - 2022-02-13

This is a fairly small release, primarily to bump substrate dependencies to their latest versions.

The main breaking change is fairly small: #804. Here, the BlockNumber associated type has been removed from Config entirely, since it wasn't actually needed anywhere in Subxt. Additionally, the constraints on each of those associated types in Config were made more precise, primarily to tidy things up (but this should result in types more easily being able to meet the requirements here). If you use custom Config, the fix is simply to remove the BlockNumber type. If you also use the Config trait in your own functions and depend on those constraints, you may be able to define a custom MyConfig type which builds off Config and adds back any additional bounds that you want.

Note worthy PRs merged since the last release:

Added

  • Add find last function (#821)
  • Doc: first item is current version comment (#817)

Changed

  • Remove unneeded Config bounds and BlockNumber associated type (#804)

v0.26.0

24 Jan 17:10
v0.26.0
d92352a
Compare
Choose a tag to compare

[0.26.0] - 2022-01-24

This release adds a number of improvements, most notably:

  • We make Substrate dependencies optional (#760), which makes WASM builds both smaller and more reliable. To do this, we re-implement some core types like AccountId32, MultiAddress and MultiSignature internally.
  • Allow access to storage entries (#774) and runtime API's (#777) from some block. This is part of a move towards a more "block centric" interface, which will better align with the newly available chainHead style RPC interface.
  • Add RPC methods for the new chainHead style interface (see https://paritytech.github.io/json-rpc-interface-spec/). These are currently unstable, but will allow users to start experimenting with this new API if their nodes support it.
  • More advanced type substitution is now possible in the codegen interface (#735).

This release introduces a number of breaking changes that can be generally be fixed with mechanical tweaks to your code. The notable changes are described below.

Make Storage API more Block-centric

See #774. This PR makes the Storage API more consistent with the Events API, and allows access to it from a given block as part of a push to provide a more block centric API that will hopefully be easier to understand, and will align with the new RPC chainHead style RPC interface.

Before, your code will look like:

let a = api.storage().fetch(&staking_bonded, None).await?;

After, it should look like:

let a = api.storage().at(None).await?.fetch(&staking_bonded).await?;

Essentially, the final parameter for choosing which block to call some method at has been moved out of the storage method itself and is now provided to instantiate the storage API, either explicitly via an .at(optional_block_hash) as above, or implicitly when calling block.storage() to access the same storage methods for some block.

An alternate way to access the same storage (primarily used if you have subscribed to blocks or otherwise are working with some block) now is:

let block = api.blocks().at(None).await?
let a = block.storage().fetch(&staking_bonded, None).await?;

More advanced type substitution in codegen

See #735. Previously, you could perform basic type substitution like this:

#[subxt::subxt(runtime_metadata_path = "../polkadot_metadata.scale")]
pub mod node_runtime {
    #[subxt::subxt(substitute_type = "sp_arithmetic::per_things::Foo")]
    use crate::Foo;
}

This example would use crate::Foo every time an sp_arithmetic::per_things::Foo was encountered in the codegen. However, this was limited; the substitute type had to have the name number and order of generic parameters for this to work.

We've changed the interface above into:

#[subxt::subxt(
    runtime_metadata_path = "../polkadot_metadata.scale",
    substitute_type(
        type = "sp_arithmetic::per_things::Foo<A, B, C>",
        with = "crate::Foo<C>"
    )
)]
pub mod node_runtime {}

In this example, we can (optionally) specify the generic parameters we expect to see on the original type ("type"), and then of those, decide which should be present on the substitute type ("with"). If no parameters are provided at all, we'll get the same behaviour as before. This allows much more flexibility when defining substitute types.

Optional Substrate dependencies

See #760. Subxt now has a "substrate-compat" feature (enabled by default, and disabled for WASM builds). At present, enabling this feature simply exposes the PairSigner (which was always available before), allowing transactions to be signed via Substrate signer logic (as before). When disabled, you (currently) must bring your own signer implementation, but in return we can avoid bringing in a substantial number of Substrate dependencies in the process.

Regardless, this change also tidied up and moved various bits and pieces around to be consistent with this goal. To address some common moves, previously we'd have:

use subxt::{
    ext::{
        sp_core::{ sr25519, Pair },
        sp_runtime::{ AccountId32, generic::Header },
    },
    tx::{
        Era,
        PlainTip,
        PolkadotExtrinsicParamsBuilder
    }
};

And now this would look more like:

// `sp_core` and `sp_runtime` are no longer exposed via `ext`; add the crates yourself at matching versions to use:
use sp_core::{
    sr25519,
    Pair,
};
use subxt::{
    // You'll often want to use the "built-in" `AccountId32` now instead of the `sp_runtime` version:
    utils::AccountId32,
    // traits used in our `Config` trait are now provided directly in this module:
    config::Header,
    // Polkadot and Substrate specific Config types are now in the relevant Config section:
    config::polkadot::{
        Era,
        PlainTip,
        PolkadotExtrinsicParamsBuilder
    }
}

Additionally, the type Hashing in the Config trait is now called Hasher, to clarify what it is, and types returned directly from the RPC calls now all live in crate::rpc::types, rather than sometimes living in Substrate crates.

Some other note worthy PRs that were merged since the last release:

Added

  • Add block-centric Storage API (#774)
  • Add chainHead RPC methods (#766)
  • Allow for remapping type parameters in type substitutions (#735)
  • Add ability to set custom metadata etc on OnlineClient (#794)
  • Add Cargo.lock for deterministic builds (#795)
  • Add API to execute runtime calls (#777)
  • Add bitvec-like generic support to the scale-bits type for use in codegen (#718)
  • Add --derive-for-type to cli (#708)

Changed

  • rename subscribe_to_updates() to updater() (#792)
  • Expose Update (#791)
  • Expose version info in CLI tool with build-time obtained git hash (#787)
  • Implement deserialize on AccountId32 (#773)
  • Codegen: Preserve attrs and add #[allow(clippy::all)] (#784)
  • make ChainBlockExtrinsic cloneable (#778)
  • Make sp_core and sp_runtime dependencies optional, and bump to latest (#760)
  • Make verbose rpc error display (#758)
  • rpc: Expose the subscription ID for RpcClientT (#733)
  • events: Fetch metadata at arbitrary blocks (#727)

Fixed

  • Fix decoding events via .as_root_event() and add test (#767)
  • Retain Rust code items from mod decorated with subxt attribute (#721)

v0.25.0

16 Nov 15:29
v0.25.0
428bc35
Compare
Choose a tag to compare

[0.25.0] - 2022-11-16

This release resolves the parity-util-mem crate several version guard by updating substrate related dependencies which makes
it possible to have other substrate dependencies in tree again along with subxt.

In addition the release has several API improvements in the dynamic transaction API along with that subxt now compiles down to WASM.

Notable PRs merged:

Added

  • Add getters for Module (#697)
  • add wasm support (#700)
  • Extend the new api.blocks() to be the primary way to subscribe and fetch blocks/extrinsics/events (#691)
  • Add runtime_metadata_url to pull metadata directly from a node (#689)
  • Implement BlocksClient for working with blocks (#671)
  • Allow specifying the subxt crate path for generated code (#664)
  • Allow taking out raw bytes from a SubmittableExtrinsic (#683)
  • Add DecodedValueThunk to allow getting bytes back from dynamic queries (#680)

Changed

  • Update substrate crates (#709)
  • Make working with nested queries a touch easier (#714)
  • Upgrade to scale-info 2.3 and fix errors (#704)
  • No need to entangle Signer and nonce now (#702)
  • error: RpcError with custom client error (#694)
  • into_encoded() for consistency (#685)
  • make subxt::Config::Extrinsic Send (#681)
  • Refactor CLI tool to give room for growth (#667)
  • expose jsonrpc-core client (#672)
  • Upgrade clap to v4 (#678)

v0.24.0

22 Sep 16:29
v0.24.0
75e383d
Compare
Choose a tag to compare

This release has a bunch of smaller changes and fixes. The breaking changes are fairly minor and should be easy to address if encountered. Notable additions are:

  • Allowing the underlying RPC implementation to be swapped out (#634). This makes jsonrpsee an optional dependency, and opens the door for Subxt to be integrated into things like light clients, since we can decide how to handle RPC calls.
  • A low level "runtime upgrade" API is exposed, giving more visibility into when node updates happen in case your application needs to handle them.
  • scale-value and scale-decode dependencies are bumped. The main effect of this is that bitvec is no longer used under the hood in the core of Subxt, which helps to remove one hurdle on the way to being able to compile it to WASM.

Notable PRs merged:

Added

  • feat: add low-level runtime upgrade API (#657)
  • Add accessor for StaticTxPayload::call_data (#660)
  • Store type name of a field in event metadata, and export EventFieldMetadata (#656 and #654)
  • Allow generalising over RPC implementation (#634)
  • Add conversion and default functions for NumberOrHex (#636)
  • Allow creating/submitting unsigned transactions, too. (#625)
  • Add Staking Miner and Introspector to usage list (#647)

Changed

  • Bump scale-value and scale-decode (#659)
  • Tweak 0.23 notes and add another test for events (#618)
  • Specialize metadata errors (#633)
  • Simplify the TxPayload trait a little (#638)
  • Remove unnecessary async (#645)
  • Use 'sp_core::Hxxx' for all hash types (#623)

Fixed

  • Fix history_depth testing (#662)
  • Fix codegen for codec::Compact as type parameters (#651)
  • Support latest substrate release (#653)