# payment_queryInfo - FLOP RPC Method

Estimates the fee for an encoded extrinsic on FLOP. Returns the weight, dispatch class, and partial fee so you can display costs to users or verify sufficient balance before submitting transactions.

> **Why FLOP?** Build on the Substrate Proof of Inference Layer 1 built for autonomous AI agents with Proof of Inference with TOPLOC activation commitments, full historical archive state from genesis, and JSON-RPC v2 archive and chainHead APIs.

## When to Use This Method

`payment_queryInfo` is essential for AI agent builders, FLOP miners, indexers, and Substrate developers:

- **Fee Display** -- Show users the estimated transaction cost before they sign on FLOP
- **Balance Validation** -- Verify the sender has sufficient funds to cover the fee plus the transfer amount for Proof of Inference settlement, 1-second BABE blocks with AlephBFT finality, archive state queries, and HTLC atomic swaps
- **Transaction Planning** -- Compare fees across different extrinsic types to optimize costs
- **Batch Cost Estimation** -- Estimate the total cost of batch transactions before submission

## Best Practices

- Fees may change before extrinsic inclusion due to network conditions
- The `partialFee` is returned in planck (smallest unit of the native token)
- Test with actual encoded extrinsic data for the most accurate fee estimate
- Use `payment_queryFeeDetails` for a component-level fee breakdown

## Request Parameters

- `extrinsic` (`String, required`): Hex-encoded signed or unsigned extrinsic
- `blockHash` (`String, optional`): Block hash for fee calculation context; defaults to the best block if omitted

## Request Example

```json
{
  "jsonrpc": "2.0",
  "method": "payment_queryInfo",
  "params": ["0x4d0284ff..."],
  "id": 1
}
```

## Response Fields

- `weight` (`Object, required`): The dispatch weight of the extrinsic, containing refTime (compute) and proofSize (storage proof)
- `class` (`String, required`): The dispatch class: "Normal", "Operational", or "Mandatory"
- `partialFee` (`String, required`): The estimated fee in the chain's smallest unit (e.g., Planck for Polkadot). Does not include tip

## Successful Response

```json
{
  "jsonrpc": "2.0",
  "id": 1,
  "result": {
    "weight": {
      "refTime": 216215000,
      "proofSize": 3593
    },
    "class": "Normal",
    "partialFee": "157000152"
  }
}
```

## Error Responses

### Error Response

- Code: `-32603`

```json
{
  "jsonrpc": "2.0",
  "id": 1,
  "error": {
    "code": -32603,
    "message": "Unable to query dispatch info"
  }
}
```

## Code Examples

cURL
JavaScript
Python
Rust

```bash
curl -X POST https://api-flop-testnet.n.dwellir.com/YOUR_API_KEY \
  -H "Content-Type: application/json" \
  -d '{
    "jsonrpc": "2.0",
    "method": "payment_queryInfo",
    "params": ["0x4d0284ff..."],
    "id": 1
  }'
```

```javascript
// Using @polkadot/api (recommended)
import { ApiPromise, WsProvider } from '@polkadot/api';

const provider = new WsProvider('wss://api-flop-testnet.n.dwellir.com/YOUR_API_KEY');
const api = await ApiPromise.create({ provider });

// Create a transfer extrinsic
const recipient = '5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY';
const amount = 1000000000000; // Example base-unit amount; adjust for the chain's native decimals
const transfer = api.tx.balances.transferKeepAlive(recipient, amount);

// Query fee info using a sender address
const sender = '5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY';
const info = await transfer.paymentInfo(sender);

console.log('Partial fee:', info.partialFee.toHuman());
console.log('Weight:', info.weight.toString());
console.log('Class:', info.class.toString());

await api.disconnect();

// Using fetch (HTTP JSON-RPC) with a pre-encoded extrinsic
const response = await fetch('https://api-flop-testnet.n.dwellir.com/YOUR_API_KEY', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    jsonrpc: '2.0',
    method: 'payment_queryInfo',
    params: [transfer.toHex()],
    id: 1
  })
});

const { result } = await response.json();
console.log('Fee estimate:', result.partialFee);
```

```python
import requests

def query_fee_info(extrinsic_hex, block_hash=None):
    params = [extrinsic_hex]
    if block_hash:
        params.append(block_hash)

    response = requests.post(
        'https://api-flop-testnet.n.dwellir.com/YOUR_API_KEY',
        json={
            'jsonrpc': '2.0',
            'method': 'payment_queryInfo',
            'params': params,
            'id': 1
        }
    )
    return response.json()['result']

# Query fee for a pre-built extrinsic
extrinsic_hex = '0x4d0284ff...'
info = query_fee_info(extrinsic_hex)
print(f"Partial fee: {info['partialFee']}")
print(f"Weight: {info['weight']}")
print(f"Class: {info['class']}")

# Using substrate-interface
from substrateinterface import SubstrateInterface, Keypair

substrate = SubstrateInterface(url='wss://api-flop-testnet.n.dwellir.com/YOUR_API_KEY')

# Build a transfer call
call = substrate.compose_call(
    call_module='Balances',
    call_function='transfer_keep_alive',
    call_params={
        'dest': '5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY',
        'value': 1000000000000
    }
)

# Create extrinsic for fee estimation
keypair = Keypair.create_from_uri('//Alice')
extrinsic = substrate.create_signed_extrinsic(call=call, keypair=keypair)
info = substrate.get_payment_info(call=call, keypair=keypair)
print(f"Estimated fee: {info['partialFee']}")
```

```rust
use serde_json::json;
use serde::Deserialize;

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct DispatchInfo {
    weight: Weight,
    class: String,
    partial_fee: String,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct Weight {
    ref_time: u64,
    proof_size: u64,
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = reqwest::Client::new();
    let extrinsic_hex = "0x4d0284ff..."; // pre-encoded extrinsic

    let response = client
        .post("https://api-flop-testnet.n.dwellir.com/YOUR_API_KEY")
        .json(&json!({
            "jsonrpc": "2.0",
            "method": "payment_queryInfo",
            "params": [extrinsic_hex],
            "id": 1
        }))
        .send()
        .await?;

    let result: serde_json::Value = response.json().await?;
    let info: DispatchInfo = serde_json::from_value(result["result"].clone())?;

    println!("Partial fee: {}", info.partial_fee);
    println!("Weight: refTime={}, proofSize={}", info.weight.ref_time, info.weight.proof_size);
    println!("Class: {}", info.class);
    Ok(())
}
```

## Common Use Cases

### 1. Pre-Transaction Fee Display

Show fees to users before they confirm a transaction:

```javascript
import { ApiPromise, WsProvider } from '@polkadot/api';
import { BN } from '@polkadot/util';

async function displayFeeEstimate(api, extrinsic, senderAddress) {
  const [info, properties] = await Promise.all([
    extrinsic.paymentInfo(senderAddress),
    api.rpc.system.properties()
  ]);

  const decimals = properties.tokenDecimals.toJSON()[0];
  const symbol = properties.tokenSymbol.toJSON()[0];
  const fee = info.partialFee;

  // Convert to human-readable
  const divisor = new BN(10).pow(new BN(decimals));
  const whole = fee.div(divisor);
  const fractional = fee.mod(divisor).toString().padStart(decimals, '0');

  const formatted = `${whole}.${fractional.slice(0, 6)} ${symbol}`;
  console.log(`Estimated fee: ${formatted}`);
  console.log(`Dispatch class: ${info.class.toString()}`);

  return { fee: fee.toString(), formatted, class: info.class.toString() };
}
```

### 2. Sufficient Balance Check

Verify the sender can afford the transaction plus fees:

```javascript
async function canAffordTransaction(api, senderAddress, recipient, amount) {
  const transfer = api.tx.balances.transferKeepAlive(recipient, amount);
  const [info, account] = await Promise.all([
    transfer.paymentInfo(senderAddress),
    api.query.system.account(senderAddress)
  ]);

  const fee = info.partialFee.toBigInt();
  const transferAmount = BigInt(amount);
  const totalCost = fee + transferAmount;
  const freeBalance = account.data.free.toBigInt();

  // Account for existential deposit
  const existentialDeposit = api.consts.balances.existentialDeposit.toBigInt();
  const available = freeBalance - existentialDeposit;

  const canAfford = available >= totalCost;

  console.log(`Free balance: ${freeBalance}`);
  console.log(`Total cost (amount + fee): ${totalCost}`);
  console.log(`Can afford: ${canAfford}`);

  return canAfford;
}
```

### 3. Compare Fees Across Transaction Types

Estimate fees for different operations to find the cheapest approach:

```javascript
async function compareFees(api, sender) {
  const recipient = '5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY';
  const amount = 1000000000000;

  // Different transaction types
  const extrinsics = {
    'transfer': api.tx.balances.transferKeepAlive(recipient, amount),
    'transferAll': api.tx.balances.transferAll(recipient, false),
    'batchTransfer': api.tx.utility.batchAll([
      api.tx.balances.transferKeepAlive(recipient, amount / 2),
      api.tx.balances.transferKeepAlive(recipient, amount / 2)
    ])
  };

  const fees = {};
  for (const [name, ext] of Object.entries(extrinsics)) {
    const info = await ext.paymentInfo(sender);
    fees[name] = {
      partialFee: info.partialFee.toHuman(),
      weight: info.weight.toString(),
      class: info.class.toString()
    };
  }

  console.table(fees);
  return fees;
}
```

## Related Methods

- [`author_submitExtrinsic`](https://www.dwellir.com/docs/flop/author_submitExtrinsic) -- Submit the extrinsic after verifying the fee
- [`payment_queryFeeDetails`](https://www.dwellir.com/docs/flop/payment_queryFeeDetails) -- Get a detailed fee breakdown (base fee, length fee, weight fee)
- [`system_properties`](https://www.dwellir.com/docs/flop/system_properties) -- Get token decimals and symbol for formatting the fee
- [`state_call`](https://www.dwellir.com/docs/flop/state_call) -- Call `TransactionPaymentApi` directly for advanced fee queries
- [`author_pendingExtrinsics`](https://www.dwellir.com/docs/flop/author_pendingExtrinsics) -- Check pending extrinsics in the pool
