Skip to content

Commit 3ef3ae2

Browse files
committed
Add tutorial for calculating transaction fees in Polkadot
1 parent dd07afa commit 3ef3ae2

File tree

2 files changed

+258
-1
lines changed

2 files changed

+258
-1
lines changed
Lines changed: 258 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1,258 @@
1-
TODO
1+
---
2+
title: Calculate Transaction Fees
3+
description: Learn how to calculate transaction fees for transfers between accounts using Polkadot-API, Polkadot.js API, and Polkadot-JS Apps UI.
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
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.
52+
53+
Create a file named `papi-fee-calculator.ts`:
54+
55+
```typescript title="papi-fee-calculator.ts"
56+
import { createClient } from "polkadot-api";
57+
import { withPolkadotSdkCompat } from "polkadot-api/polkadot-sdk-compat";
58+
import { polkadotTestNet } from "@polkadot-api/descriptors";
59+
import { getWsProvider } from "polkadot-api/ws-provider";
60+
61+
async function calculateFees() {
62+
// Connect to chain
63+
const client = createClient(
64+
withPolkadotSdkCompat(getWsProvider("INSERT_WS_ENDPOINT"))
65+
);
66+
67+
// Get typed API
68+
const api = client.getTypedApi(polkadotTestNet);
69+
70+
// Define sender and recipient addresses
71+
const aliceAddress = "INSERT_ALICE_ADDRESS";
72+
const bobAddress = "INSERT_BOB_ADDRESS";
73+
74+
// Amount to transfer (1 DOT = 10^10 plancks)
75+
const amount = 1_000_000_000_000n; // 1 DOT
76+
77+
try {
78+
// Create the transaction
79+
const tx = api.tx.Balances.transfer_keep_alive({
80+
dest: {
81+
type: "Id",
82+
value: bobAddress,
83+
},
84+
value: amount,
85+
});
86+
87+
// Estimate fees
88+
const estimatedFees = await tx.getEstimatedFees(aliceAddress);
89+
90+
console.log(`Estimated fee: ${Number(estimatedFees) / 1e10} DOT`);
91+
console.log(`Transaction amount: ${Number(amount) / 1e10} DOT`);
92+
console.log(
93+
`Total deducted: ${Number(estimatedFees + amount) / 1e10} DOT`
94+
);
95+
} catch (error) {
96+
console.error("Error calculating fees:", error);
97+
} finally {
98+
// Clean up
99+
client.destroy();
100+
}
101+
}
102+
103+
calculateFees();
104+
```
105+
106+
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.
107+
108+
Key aspects of the code:
109+
110+
- **Transaction creation**: The `api.tx.Balances.transfer_keep_alive()` method constructs a balance transfer transaction
111+
- **`dest` parameter**: Specifies the recipient using a `MultiAddress` type with `Id` variant
112+
- **`getEstimatedFees()`**: Returns the estimated fee in plancks (the smallest unit, where 1 DOT = 10^10 plancks)
113+
- The method applies a dummy signature internally to simulate the transaction
114+
115+
Execute the script using `tsx`:
116+
117+
```bash
118+
npx tsx papi-fee-calculator.ts
119+
```
120+
121+
You should see output similar to:
122+
123+
<div class="termynal" data-termynal>
124+
<span data-ty="input"><span class="file-path"></span>npx tsx papi-fee-calculator.ts</span>
125+
<span data-ty="progress"></span>
126+
<span data-ty>Estimated fee: 0.0014668864 DOT</span>
127+
<span data-ty>Transaction amount: 100 DOT</span>
128+
<span data-ty>Total deducted: 100.0014668864 DOT</span>
129+
</div>
130+
131+
## Polkadot.js API
132+
133+
[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.
134+
135+
In the same project directory (or a new one), install the Polkadot.js packages:
136+
137+
```bash
138+
npm install @polkadot/api
139+
```
140+
141+
Create a file named `polkadotjs-fee-calculator.ts`:
142+
143+
```typescript title="polkadotjs-fee-calculator.ts"
144+
import { ApiPromise, WsProvider } from "@polkadot/api";
145+
146+
async function calculateFees() {
147+
// Connect to chain
148+
const wsProvider = new WsProvider("INSERT_WS_ENDPOINT");
149+
const api = await ApiPromise.create({ provider: wsProvider });
150+
151+
// Wait for API to be ready
152+
await api.isReady;
153+
154+
// Define sender and recipient addresses
155+
const aliceAddress = "INSERT_ALICE_ADDRESS";
156+
const bobAddress = "INSERT_BOB_ADDRESS";
157+
158+
// Amount to transfer (1 DOT = 10^10 plancks)
159+
const amount = 1_000_000_000_000n; // 1 DOT
160+
161+
try {
162+
// Create the transaction
163+
const tx = api.tx.balances.transferKeepAlive(bobAddress, amount);
164+
165+
// Get payment information
166+
const paymentInfo = await tx.paymentInfo(aliceAddress);
167+
168+
console.log(`Estimated fee: ${Number(paymentInfo.partialFee.toBigInt()) / 1e10} DOT`);
169+
console.log(`Transaction amount: ${Number(amount) / 1e10} DOT`);
170+
console.log(
171+
`Total deducted: ${Number(paymentInfo.partialFee.toBigInt() + amount) / 1e10} DOT`
172+
);
173+
} catch (error) {
174+
console.error("Error calculating fees:", error);
175+
} finally {
176+
// Clean up
177+
await api.disconnect();
178+
}
179+
}
180+
181+
calculateFees();
182+
```
183+
184+
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.
185+
186+
Key aspects of the code:
187+
188+
- **Transaction creation**: The `api.tx.balances.transferKeepAlive()` method constructs a balance transfer transaction
189+
- **`paymentInfo()`**: Applies a dummy signature and queries the RPC endpoint for fee estimation
190+
- **Return values**: The `partialFee` property contains the estimated fee in the smallest unit (plancks)
191+
192+
Execute the script using `tsx`:
193+
194+
```bash
195+
npx tsx polkadotjs-fee-calculator.ts
196+
```
197+
198+
You should see output similar to:
199+
200+
<div class="termynal" data-termynal>
201+
<span data-ty="input"><span class="file-path"></span>npx tsx polkadotjs-fee-calculator.ts</span>
202+
<span data-ty="progress"></span>
203+
<span data-ty>Estimated fee: 0.0014668864 DOT</span>
204+
<span data-ty>Transaction amount: 100 DOT</span>
205+
<span data-ty>Total deducted: 100.0014668864 DOT</span>
206+
</div>
207+
208+
## Polkadot-JS Apps Interface
209+
210+
For non-programmatic fee inspection, the PolkadotJS Apps interface provides a visual way to estimate transaction fees.
211+
212+
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).
213+
214+
### Estimate Fees via Transfer Interface
215+
216+
To see fees before submitting a transfer:
217+
218+
1. Navigate to **Accounts** > **Accounts** in the top menu
219+
2. Choice an account and click **send**
220+
3. Fill in the transfer details:
221+
- **Send to address**: Enter Bob's address
222+
- **Amount**: Enter the amount you wish to transfer (e.g., 1 DOT)
223+
4. Click **Sign and Submit**
224+
5. The transaction fee will be displayed in the confirmation dialog before you sign
225+
226+
![](/images/chain-interactions/send-transactions/calculate-transaction-fees/calculate-transaction-fees.gif)
227+
228+
## Where to Go Next
229+
230+
Now that you can calculate transaction fees, explore related guides to send transactions and manage fees in your applications.
231+
232+
<div class="grid cards" markdown>
233+
234+
- <span class="badge guide">Guide</span> __Pay Fees with Different Tokens__
235+
236+
---
237+
238+
Learn how to send transactions while paying fees using alternative tokens instead of the native chain token.
239+
240+
[:octicons-arrow-right-24: Get Started](/chain-interactions/send-transactions/pay-fees-with-different-tokens/)
241+
242+
- <span class="badge guide">Guide</span> __Send Transactions with SDKs__
243+
244+
---
245+
246+
Learn how to send signed transactions using Polkadot-API and Polkadot.js API libraries.
247+
248+
[:octicons-arrow-right-24: Get Started](/chain-interactions/send-transactions/with-sdks/)
249+
250+
- <span class="badge guide">Guide</span> __Query Chain Data__
251+
252+
---
253+
254+
Explore different methods for querying blockchain data using REST APIs, SDKs, and runtime API calls.
255+
256+
[:octicons-arrow-right-24: Get Started](/chain-interactions/query-data/query-sdks/)
257+
258+
</div>
1.02 MB
Loading

0 commit comments

Comments
 (0)