Send a Transaction While Paying the Fee with a Different Token¶
Introduction¶
Polkadot SDK runtimes can let accounts pay transaction fees in an asset other than the chain's native token. This capability comes from the ChargeAssetTxPayment transaction extension, which adds an optional asset ID to each transaction. When the asset ID is set, the runtime charges the fee in that asset. When it is not set, the fee falls back to the native token.
This tutorial explains how the extension works and uses Subxt, Parity's Rust library for Polkadot SDK-based chains, to send a native token transfer while paying the fee in another asset. The same pattern applies to any runtime that includes the extension.
Third-party client libraries also support this extension, for example Polkadot API (PAPI) and Polkadot.js API. For a walkthrough on Polkadot Hub, see Pay Transaction Fees with Different Tokens on developers.polkadot.com.
How the Extension Works¶
The Polkadot SDK provides two pallets that implement a ChargeAssetTxPayment extension. Both wrap the Transaction Payment pallet and replace its transaction extension in the runtime:
- Asset Conversion Transaction Payment pallet: Converts the fee calculated in the native asset into the amount required of the chosen asset by swapping through the Asset Conversion pallet. The asset needs a liquidity pool with the native token.
- Asset Transaction Payment pallet: Converts the fee calculated by the Transaction Payment pallet into the chosen asset with a fungibles adapter.
To support this feature in your own runtime, include one of these pallets alongside the Transaction Payment pallet in construct_runtime and use its ChargeAssetTxPayment extension in place of the Transaction Payment extension.
On the client side, you set the asset ID in the transaction's extension parameters. The asset ID type depends on the runtime. The example in this tutorial targets a runtime whose asset ID is an XCM Location.
Prerequisites¶
This tutorial needs a running chain that includes the extension and an account that holds a fee asset with a liquidity pool. The steps below use Chopsticks, a third-party tool, to fork a chain that meets these requirements locally. If you run your own runtime with the extension, point the example at your node instead and adjust the asset ID, the Assets pallet index, and the funded account.
- Rust toolchain (latest stable) and Cargo.
- Chopsticks, or a node of your own runtime that includes the extension.
Start a Local Chain¶
Fork a chain that includes the extension with Chopsticks:
This command starts a local fork at ws://localhost:8000 using the polkadot-asset-hub.yml configuration, which gives Alice's account a balance of the asset that the example uses for fees. If you use a different chain or configuration, make sure the account you sign with holds the fee asset.
Set Up Your Project¶
-
Create a new Rust project:
-
Install the Subxt CLI to download chain metadata:
-
Download the metadata from the running chain:
Note
Ensure your chain is running at
ws://localhost:8000before downloading the metadata. If you use your own node, pass its endpoint instead, for examplews://127.0.0.1:9944. -
Update
Cargo.tomlwith the required dependencies:Cargo.toml[package] name = "subxt-fee-payment-example" version = "0.1.0" edition = "2021" [[bin]] name = "fee_payment_transaction" path = "src/bin/fee_payment_transaction.rs" [dependencies] codec = { package = "parity-scale-codec", version = "3", features = ["derive"] } subxt = { version = "0.50.1", features = ["jsonrpsee", "native"] } subxt-signer = { version = "0.50.1", features = ["sr25519"] } tokio = { version = "1.44.2", features = ["macros", "rt-multi-thread"] } -
Create the source file:
Implementation¶
The following sections cover how to set up imports and constants, create a transaction signer, connect to the chain, and send a native token transfer while paying fees in another asset.
Import Dependencies and Define Constants¶
First, generate types from the chain metadata using the #[subxt::subxt()] macro. The derive_for_type attribute ensures the Location type implements the traits needed for encoding. Then define a custom AssetPaymentConfig where type AssetId = Location, which lets you pass an XCM location as the fee payment asset. Finally, define the endpoint, transfer amount, Assets pallet index, and fee asset ID:
use subxt::config::{Config, DefaultExtrinsicParamsBuilder, DefaultTransactionExtensions, PolkadotConfig};
use subxt::utils::AccountId32;
use subxt::{OnlineClient, SubstrateConfig};
use subxt_signer::sr25519::dev;
// Generate types from the chain metadata with Location trait derives
#[subxt::subxt(
runtime_metadata_path = "metadata/runtime.scale",
derive_for_type(
path = "staging_xcm::v5::location::Location",
derive = "Clone, Eq, PartialEq, codec::Encode",
recursive
)
)]
pub mod runtime {}
// Import XCM location types from the generated metadata module
use runtime::runtime_types::staging_xcm::v5::{
junction::Junction,
junctions::Junctions,
location::Location,
};
// Define a custom config where AssetId is an XCM Location
#[derive(Debug, Default, Clone)]
pub struct AssetPaymentConfig;
impl Config for AssetPaymentConfig {
type AccountId = <PolkadotConfig as Config>::AccountId;
type Address = <PolkadotConfig as Config>::Address;
type Signature = <PolkadotConfig as Config>::Signature;
type Hasher = <PolkadotConfig as Config>::Hasher;
type Header = <SubstrateConfig as Config>::Header;
type TransactionExtensions = DefaultTransactionExtensions<AssetPaymentConfig>;
type AssetId = Location;
}
// WebSocket endpoint of the node (the Chopsticks fork in this tutorial)
const NODE_URL: &str = "ws://localhost:8000";
// Amount to transfer, in the chain's smallest unit
const TRANSFER_AMOUNT: u128 = 3_000_000_000;
// Index of the Assets pallet in the runtime
const ASSETS_PALLET_INDEX: u8 = 50;
// ID of the asset used to pay fees (an asset Alice holds in the Chopsticks config)
const FEE_ASSET_ID: u128 = 1984;
Create a Signer and Connect¶
Create a signer using Alice's development account and connect to the chain. The OnlineClient is parameterized with AssetPaymentConfig instead of the default PolkadotConfig:
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
// Connect to the node
let api = OnlineClient::<AssetPaymentConfig>::from_url(NODE_URL).await?;
println!("Connected to {}", NODE_URL);
// Anchor to the current block
let at_block = api.at_current_block().await?;
// Create Alice's dev keypair
let alice = dev::alice();
println!("Sender (Alice): {}", AccountId32::from(alice.public_key()));
Create the Transaction¶
Create a standard transfer that sends native tokens to Bob's development account while keeping Alice's account alive:
// Create the balance transfer transaction to Bob
let dest = AccountId32::from(dev::bob().public_key());
let tx = runtime::transactions()
.balances()
.transfer_keep_alive(dest.into(), TRANSFER_AMOUNT);
Sign and Submit with Alternative Fee Payment¶
The key step is setting the asset ID in the ChargeAssetTxPayment extension parameters. In this runtime, the fee asset is identified by its XCM location relative to the chain: PalletInstance holds the index of the Assets pallet and GeneralIndex holds the asset's ID in that pallet.
Use DefaultExtrinsicParamsBuilder with tip_of(0, asset_location) to specify the fee asset. The first argument is the tip amount (0), and the second is the XCM Location. Instead of calling sign_and_submit_then_watch_default, pass the custom tx_params to sign_and_submit_then_watch:
// Define the fee asset location in XCM format
let asset_location = Location {
parents: 0,
interior: Junctions::X2([
Junction::PalletInstance(ASSETS_PALLET_INDEX),
Junction::GeneralIndex(FEE_ASSET_ID),
]),
};
// Build transaction params to pay fees with the alternative asset
let tx_params = DefaultExtrinsicParamsBuilder::<AssetPaymentConfig>::new()
.tip_of(0, asset_location)
.build();
// Sign, submit, and watch for finalization
println!("Signing and submitting transaction...");
let progress = at_block
.transactions()
.sign_and_submit_then_watch(&tx, &alice, tx_params)
.await?;
let in_block = progress.wait_for_finalized().await?;
let block_hash = in_block.block_hash();
let events = in_block.wait_for_success().await?;
// Display transaction results
println!("\nTransaction finalized in block: {:?}", block_hash);
println!("\nEvents:");
for event in events.iter() {
let event = event?;
println!(
" {}.{}",
event.pallet_name(),
event.event_name()
);
}
Full Code¶
Complete Code
use subxt::config::{Config, DefaultExtrinsicParamsBuilder, DefaultTransactionExtensions, PolkadotConfig};
use subxt::utils::AccountId32;
use subxt::{OnlineClient, SubstrateConfig};
use subxt_signer::sr25519::dev;
// Generate types from the chain metadata with Location trait derives
#[subxt::subxt(
runtime_metadata_path = "metadata/runtime.scale",
derive_for_type(
path = "staging_xcm::v5::location::Location",
derive = "Clone, Eq, PartialEq, codec::Encode",
recursive
)
)]
pub mod runtime {}
// Import XCM location types from the generated metadata module
use runtime::runtime_types::staging_xcm::v5::{
junction::Junction,
junctions::Junctions,
location::Location,
};
// Define a custom config where AssetId is an XCM Location
#[derive(Debug, Default, Clone)]
pub struct AssetPaymentConfig;
impl Config for AssetPaymentConfig {
type AccountId = <PolkadotConfig as Config>::AccountId;
type Address = <PolkadotConfig as Config>::Address;
type Signature = <PolkadotConfig as Config>::Signature;
type Hasher = <PolkadotConfig as Config>::Hasher;
type Header = <SubstrateConfig as Config>::Header;
type TransactionExtensions = DefaultTransactionExtensions<AssetPaymentConfig>;
type AssetId = Location;
}
// WebSocket endpoint of the node (the Chopsticks fork in this tutorial)
const NODE_URL: &str = "ws://localhost:8000";
// Amount to transfer, in the chain's smallest unit
const TRANSFER_AMOUNT: u128 = 3_000_000_000;
// Index of the Assets pallet in the runtime
const ASSETS_PALLET_INDEX: u8 = 50;
// ID of the asset used to pay fees (an asset Alice holds in the Chopsticks config)
const FEE_ASSET_ID: u128 = 1984;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
// Connect to the node
let api = OnlineClient::<AssetPaymentConfig>::from_url(NODE_URL).await?;
println!("Connected to {}", NODE_URL);
// Anchor to the current block
let at_block = api.at_current_block().await?;
// Create Alice's dev keypair
let alice = dev::alice();
println!("Sender (Alice): {}", AccountId32::from(alice.public_key()));
// Create the balance transfer transaction to Bob
let dest = AccountId32::from(dev::bob().public_key());
let tx = runtime::transactions()
.balances()
.transfer_keep_alive(dest.into(), TRANSFER_AMOUNT);
// Define the fee asset location in XCM format
let asset_location = Location {
parents: 0,
interior: Junctions::X2([
Junction::PalletInstance(ASSETS_PALLET_INDEX),
Junction::GeneralIndex(FEE_ASSET_ID),
]),
};
// Build transaction params to pay fees with the alternative asset
let tx_params = DefaultExtrinsicParamsBuilder::<AssetPaymentConfig>::new()
.tip_of(0, asset_location)
.build();
// Sign, submit, and watch for finalization
println!("Signing and submitting transaction...");
let progress = at_block
.transactions()
.sign_and_submit_then_watch(&tx, &alice, tx_params)
.await?;
let in_block = progress.wait_for_finalized().await?;
let block_hash = in_block.block_hash();
let events = in_block.wait_for_success().await?;
// Display transaction results
println!("\nTransaction finalized in block: {:?}", block_hash);
println!("\nEvents:");
for event in events.iter() {
let event = event?;
println!(
" {}.{}",
event.pallet_name(),
event.event_name()
);
}
Ok(())
}
Run the Script¶
Expected Output¶
When you run the script successfully, you should see output similar to the following. The exact list of events depends on the runtime and on the state of the accounts involved.
Connected to ws://localhost:8000 Sender (Alice): 5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY Signing and submitting transaction... Transaction finalized in block: 0x90c92e4dca64631ab4ccaabb14273cebbb3d59205db437dfcf9ace91452b1434 Events: Assets.Withdrawn Balances.Withdraw Assets.Deposited AssetConversion.SwapCreditExecuted Balances.Upgraded System.NewAccount Balances.Endowed Balances.Transfer Balances.Deposit AssetTxPayment.AssetTxFeePaid System.ExtrinsicSuccess
The key events to look for are:
AssetTxPayment: Confirms the fees were paid using the alternative asset.AssetConversion: The alternative asset was swapped to cover native fees.Balances: The transfer was executed and deposit and withdrawal events were emitted.System: The transaction completed successfully.
Conclusion¶
The ChargeAssetTxPayment extension lets users and applications pay fees in the assets they hold, on any runtime that includes it. On the client side, the only change is setting the fee asset in the transaction's extension parameters, using the asset ID type that the runtime expects.
Where to Go Next¶
-
Guide Send Transactions with SDKs
Learn how to build, sign, and submit transactions with Subxt.
-
Guide Calculate Transaction Fees
Understand how to estimate transaction fees before submitting.
| Created: November 17, 2026