Skip to content

Commit b91301c

Browse files
nhussein11brunopgalvaoCopiloteshaben0xlukem
authored
Add estimate fee tx (#1279)
* Add tutorial for calculating transaction fees in Polkadot * \fix: snippets * Apply suggestions from code review Co-authored-by: Bruno Galvao <brunopgalvao@gmail.com> Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * fix: adding endpoint * Apply suggestions from code review Co-authored-by: Lucas Malizia <131050418+0xlukem@users.noreply.github.com> * styling * Apply suggestions from code review * improve description * fix --------- Co-authored-by: Bruno Galvao <brunopgalvao@gmail.com> Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> Co-authored-by: Erin Shaben <eshaben@icloud.com> Co-authored-by: Lucas Malizia <131050418+0xlukem@users.noreply.github.com> Co-authored-by: 0xlukem <lucas.malizia27@gmail.com>
1 parent d59089b commit b91301c

File tree

6 files changed

+264
-1
lines changed

6 files changed

+264
-1
lines changed
Lines changed: 162 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1,162 @@
1-
TODO
1+
---
2+
title: Calculate Transaction Fees
3+
description: Learn how to calculate transaction fees on Polkadot using Polkadot-API, Polkadot.js API, and the Polkadot.js Apps UI to estimate transfer costs.
4+
categories: Basics, Transactions, Developer Tools
5+
---
6+
7+
# Calculate Transaction Fees
8+
9+
## Introduction
10+
11+
Transaction fees are essential costs for executing operations on Polkadot and its parachains. Understanding how to estimate these fees helps you manage account balances and build better user experiences in your applications.
12+
13+
This tutorial will guide you through different methods for calculating transaction fees.
14+
15+
## Prerequisites
16+
17+
Before starting, make sure you have:
18+
19+
- [Node.js](https://nodejs.org/){target=\_blank} version 18 or higher installed
20+
- Basic understanding of JavaScript/TypeScript
21+
- Test accounts with sufficient balance to pay transaction fees
22+
23+
!!! note
24+
Transaction fees on Polkadot are calculated based on three components: a base fee, a length fee (proportional to transaction size), and a weight fee (proportional to computational complexity). An optional tip can be added to prioritize transaction inclusion.
25+
26+
## Polkadot-API (PAPI)
27+
28+
[Polkadot-API](/reference/tools/papi){target=\_blank} is the modern, recommended library for building TypeScript applications with type safety and light client support.
29+
30+
Create a new project directory and initialize it:
31+
32+
```bash
33+
mkdir fee-calculator
34+
cd fee-calculator
35+
npm init -y && npm pkg set type=module
36+
```
37+
38+
Install the required packages:
39+
40+
```bash
41+
npm install polkadot-api
42+
npm install --save-dev typescript tsx
43+
```
44+
45+
Add the Polkadot relay chain to generate type-safe descriptors:
46+
47+
```bash
48+
npx papi add polkadotTestNet -w INSERT_WS_ENDPOINT
49+
```
50+
51+
This command downloads the latest Polkadot metadata and generates TypeScript descriptors in the `@polkadot-api/descriptors` package. Ensure to replace `INSERT_WS_ENDPOINT` with the proper websocket endpoint. For this example, we will use the Polkadot Testnet (`wss://pas-rpc.stakeworld.io/assethub`).
52+
53+
Create a file named `papi-fee-calculator.ts`:
54+
55+
```typescript title="papi-fee-calculator.ts"
56+
--8<-- 'code/chain-interactions/send-transactions/calculate-transaction-fees/papi-fee-calculator.ts'
57+
```
58+
59+
Ensure to replace `INSERT_WS_ENDPOINT` with your WebSocket endpoint, `INSERT_ALICE_ADDRESS` with the sender's address, and `INSERT_BOB_ADDRESS` with the recipient's address.
60+
61+
Key aspects of the code:
62+
63+
- **Transaction creation**: The `api.tx.Balances.transfer_keep_alive()` method constructs a balance transfer transaction.
64+
- **`dest` parameter**: Specifies the recipient using a `MultiAddress` type with `Id` variant.
65+
- **`getEstimatedFees()`**: Returns the estimated fee in plancks (the smallest unit, where 1 DOT = 10^10 plancks).
66+
- The method applies a dummy signature internally to simulate the transaction.
67+
68+
Execute the script using `tsx`:
69+
70+
```bash
71+
npx tsx papi-fee-calculator.ts
72+
```
73+
74+
You should see output similar to:
75+
76+
--8<-- 'code/chain-interactions/send-transactions/calculate-transaction-fees/papi-fee-calculator-output.html'
77+
78+
## Polkadot.js API
79+
80+
[Polkadot.js API](https://polkadot.js.org/docs/api/){target=\_blank} is a mature JavaScript/TypeScript library for interacting with Polkadot SDK-based chains, providing comprehensive RPC client functionality and transaction building capabilities.
81+
82+
In the same project directory (or a new one), install the Polkadot.js packages:
83+
84+
```bash
85+
npm install @polkadot/api
86+
```
87+
88+
Create a file named `polkadotjs-fee-calculator.ts`:
89+
90+
```typescript title="polkadotjs-fee-calculator.ts"
91+
--8<-- 'code/chain-interactions/send-transactions/calculate-transaction-fees/polkadotjs-fee-calculator.ts'
92+
```
93+
94+
Ensure to replace `INSERT_WS_ENDPOINT` with your WebSocket endpoint, `INSERT_ALICE_ADDRESS` with the sender's address, and `INSERT_BOB_ADDRESS` with the recipient's address.
95+
96+
Key aspects of the code:
97+
98+
- **Transaction creation**: The `api.tx.balances.transferKeepAlive()` method constructs a balance transfer transaction.
99+
- **`paymentInfo()`**: Applies a dummy signature and queries the RPC endpoint for fee estimation.
100+
- **Return values**: The `partialFee` property contains the estimated fee in the smallest unit (plancks).
101+
102+
Execute the script using `tsx`:
103+
104+
```bash
105+
npx tsx polkadotjs-fee-calculator.ts
106+
```
107+
108+
You should see output similar to:
109+
110+
--8<-- 'code/chain-interactions/send-transactions/calculate-transaction-fees/polkadotjs-fee-calculator-output.html'
111+
112+
## Polkadot.js Apps Interface
113+
114+
For non-programmatic fee inspection, the PolkadotJS Apps interface provides a visual way to estimate transaction fees.
115+
116+
Navigate to the [Polkadot.js Apps interface](https://polkadot.js.org/apps){target=\_blank} and ensure you're connected to the Polkadot relay chain (or your desired network).
117+
118+
### Estimate Fees via Transfer Interface
119+
120+
To see fees before submitting a transfer:
121+
122+
1. Navigate to **Accounts** > **Accounts** in the top menu.
123+
2. Choose an account and click **send**.
124+
3. Fill in the transfer details:
125+
- **Send to address**: Enter Bob's address.
126+
- **Amount**: Enter the amount you wish to transfer (e.g., 1 DOT).
127+
4. Click **Sign and Submit**.
128+
5. The transaction fee will be displayed in the confirmation dialog before you sign.
129+
130+
![](/images/chain-interactions/send-transactions/calculate-transaction-fees/calculate-transaction-fees-01.gif)
131+
132+
## Where to Go Next
133+
134+
Now that you can calculate transaction fees, explore related guides to send transactions and manage fees in your applications.
135+
136+
<div class="grid cards" markdown>
137+
138+
- <span class="badge guide">Guide</span> __Pay Fees with Different Tokens__
139+
140+
---
141+
142+
Learn how to send transactions while paying fees using alternative tokens instead of the native chain token.
143+
144+
[:octicons-arrow-right-24: Get Started](/chain-interactions/send-transactions/pay-fees-with-different-tokens/)
145+
146+
- <span class="badge guide">Guide</span> __Send Transactions with SDKs__
147+
148+
---
149+
150+
Learn how to send signed transactions using Polkadot-API and Polkadot.js API libraries.
151+
152+
[:octicons-arrow-right-24: Get Started](/chain-interactions/send-transactions/with-sdks/)
153+
154+
- <span class="badge guide">Guide</span> __Query Chain Data__
155+
156+
---
157+
158+
Explore different methods for querying blockchain data using REST APIs, SDKs, and runtime API calls.
159+
160+
[:octicons-arrow-right-24: Get Started](/chain-interactions/query-data/query-sdks/)
161+
162+
</div>
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
<div class="termynal" data-termynal>
2+
<span data-ty="input"><span class="file-path"></span>npx tsx papi-fee-calculator.ts</span>
3+
<span data-ty="progress"></span>
4+
<span data-ty>Estimated fee: 0.0014668864 DOT</span>
5+
<span data-ty>Transaction amount: 1 DOT</span>
6+
<span data-ty>Total deducted: 1.0014668864 DOT</span>
7+
</div>
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
import { createClient } from 'polkadot-api';
2+
import { withPolkadotSdkCompat } from 'polkadot-api/polkadot-sdk-compat';
3+
import { polkadotTestNet } from '@polkadot-api/descriptors';
4+
import { getWsProvider } from 'polkadot-api/ws-provider';
5+
6+
async function calculateFees() {
7+
// Connect to chain
8+
const client = createClient(
9+
withPolkadotSdkCompat(getWsProvider('INSERT_WS_ENDPOINT'))
10+
);
11+
12+
// Get typed API
13+
const api = client.getTypedApi(polkadotTestNet);
14+
15+
// Define sender and recipient addresses
16+
const aliceAddress = 'INSERT_ALICE_ADDRESS';
17+
const bobAddress = 'INSERT_BOB_ADDRESS';
18+
19+
// Amount to transfer (1 DOT = 10^10 plancks)
20+
const amount = 10_000_000_000n; // 1 DOT
21+
22+
try {
23+
// Create the transaction
24+
const tx = api.tx.Balances.transfer_keep_alive({
25+
dest: {
26+
type: 'Id',
27+
value: bobAddress,
28+
},
29+
value: amount,
30+
});
31+
32+
// Estimate fees
33+
const estimatedFees = await tx.getEstimatedFees(aliceAddress);
34+
35+
console.log(`Estimated fee: ${Number(estimatedFees) / 1e10} DOT`);
36+
console.log(`Transaction amount: ${Number(amount) / 1e10} DOT`);
37+
console.log(`Total deducted: ${Number(estimatedFees + amount) / 1e10} DOT`);
38+
} catch (error) {
39+
console.error('Error calculating fees:', error);
40+
} finally {
41+
// Clean up
42+
client.destroy();
43+
}
44+
}
45+
46+
calculateFees();
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
<div class="termynal" data-termynal>
2+
<span data-ty="input"><span class="file-path"></span>npx tsx polkadotjs-fee-calculator.ts</span>
3+
<span data-ty="progress"></span>
4+
<span data-ty>Estimated fee: 0.0014668864 DOT</span>
5+
<span data-ty>Transaction amount: 1 DOT</span>
6+
<span data-ty>Total deducted: 1.0014668864 DOT</span>
7+
</div>
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
import { ApiPromise, WsProvider } from '@polkadot/api';
2+
3+
async function calculateFees() {
4+
// Connect to chain
5+
const wsProvider = new WsProvider('INSERT_WS_ENDPOINT');
6+
const api = await ApiPromise.create({ provider: wsProvider });
7+
8+
// Wait for API to be ready
9+
await api.isReady;
10+
11+
// Define sender and recipient addresses
12+
const aliceAddress = 'INSERT_ALICE_ADDRESS';
13+
const bobAddress = 'INSERT_BOB_ADDRESS';
14+
15+
// Amount to transfer (1 DOT = 10^10 plancks)
16+
const amount = 10_000_000_000n; // 1 DOT
17+
18+
try {
19+
// Create the transaction
20+
const tx = api.tx.balances.transferKeepAlive(bobAddress, amount);
21+
22+
// Get payment information
23+
const paymentInfo = await tx.paymentInfo(aliceAddress);
24+
25+
console.log(
26+
`Estimated fee: ${Number(paymentInfo.partialFee.toBigInt()) / 1e10} DOT`
27+
);
28+
console.log(`Transaction amount: ${Number(amount) / 1e10} DOT`);
29+
console.log(
30+
`Total deducted: ${
31+
Number(paymentInfo.partialFee.toBigInt() + amount) / 1e10
32+
} DOT`
33+
);
34+
} catch (error) {
35+
console.error('Error calculating fees:', error);
36+
} finally {
37+
// Clean up
38+
await api.disconnect();
39+
}
40+
}
41+
42+
calculateFees();
1.02 MB
Loading

0 commit comments

Comments
 (0)