# state_getKeysPaged - FLOP RPC Method

Returns storage keys matching a prefix with cursor-based pagination on FLOP. This is the standard way to iterate over storage maps (like `System.Account`, `Staking.Validators`, or any pallet storage map) without loading all keys into memory at once.

> **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

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

- **Storage Map Iteration** -- Enumerate all entries in a storage map (accounts, balances, staking data) on FLOP
- **Data Export and Indexing** -- Bulk export on-chain state for analytics, indexers, and data pipelines for Proof of Inference settlement, 1-second BABE blocks with AlephBFT finality, archive state queries, and HTLC atomic swaps
- **Account Enumeration** -- List all accounts that have balances, staking positions, or other on-chain state
- **State Migration Tooling** -- Iterate storage for runtime upgrades, audits, or cross-chain migration

## Best Practices

- Always use a storage key prefix to limit the result set size
- Paginate through large key sets using the `afterKey` parameter
- Combine with `state_getStorage` to retrieve values for discovered keys
- Use `state_getMetadata` to determine the correct key prefix for each pallet

## Request Parameters

- `prefix` (`String, required`): Hex-encoded storage key prefix to filter by (e.g., the pallet+storage item hash)
- `count` (`Number, required`): Maximum number of keys to return per page (recommended: 100-1000)
- `startKey` (`String, optional`): The last key from the previous page to continue from; omit for the first page
- `blockHash` (`String, optional`): Block hash for historical query; defaults to the best block if omitted

## Request Example

```json
{
  "jsonrpc": "2.0",
  "method": "state_getKeysPaged",
  "params": [
    "0x26aa394eea5630e07c48ae0c9558cef7b99d880ec681799c0cf30e8886371da9",
    10
  ],
  "id": 1
}
```

## Response Fields

- `result` (`Array<String>, required`): Array of hex-encoded storage keys matching the prefix. Returns fewer than count entries (or empty) when the last page is reached

## Successful Response

```json
{
  "jsonrpc": "2.0",
  "id": 1,
  "result": [
    "0x26aa394eea5630e07c48ae0c9558cef7b99d880ec681799c0cf30e8886371da900a32c1508ad8e892b07be65125d4ba46",
    "0x26aa394eea5630e07c48ae0c9558cef7b99d880ec681799c0cf30e8886371da901c8237c1508a37c72e20f84b137cfb8ed",
    "0x26aa394eea5630e07c48ae0c9558cef7b99d880ec681799c0cf30e8886371da905c4d73a68eff3a32b6af8adc29e8fc0be"
  ]
}
```

## Error Responses

### Error Response

- Code: `-32603`

```json
{
  "jsonrpc": "2.0",
  "id": 1,
  "error": {
    "code": -32603,
    "message": "Internal error"
  }
}
```

## Code Examples

cURL
JavaScript
Python
Rust

```bash
# Get the first 10 System.Account storage keys
curl -X POST https://api-flop-testnet.n.dwellir.com/YOUR_API_KEY \
  -H "Content-Type: application/json" \
  -d '{
    "jsonrpc": "2.0",
    "method": "state_getKeysPaged",
    "params": [
      "0x26aa394eea5630e07c48ae0c9558cef7b99d880ec681799c0cf30e8886371da9",
      10
    ],
    "id": 1
  }'

# Continue from the last key (pagination)
curl -X POST https://api-flop-testnet.n.dwellir.com/YOUR_API_KEY \
  -H "Content-Type: application/json" \
  -d '{
    "jsonrpc": "2.0",
    "method": "state_getKeysPaged",
    "params": [
      "0x26aa394eea5630e07c48ae0c9558cef7b99d880ec681799c0cf30e8886371da9",
      10,
      "0x26aa394eea5630e07c48ae0c9558cef7b99d880ec681799c0cf30e8886371da905c4d73a68eff3a32b6af8adc29e8fc0be"
    ],
    "id": 1
  }'
```

```javascript
// Using @polkadot/api (high-level)
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 });

// Get first page of System.Account keys
const prefix = api.query.system.account.keyPrefix();
const pageSize = 100;

const firstPage = await api.rpc.state.getKeysPaged(prefix, pageSize);
console.log(`First page: ${firstPage.length} keys`);

// Iterate all pages
async function getAllKeys(api, prefix, pageSize = 100) {
  const allKeys = [];
  let startKey = undefined;

  while (true) {
    const keys = await api.rpc.state.getKeysPaged(prefix, pageSize, startKey);
    if (keys.length === 0) break;

    allKeys.push(...keys);
    startKey = keys[keys.length - 1];
    console.log(`Fetched ${allKeys.length} keys so far...`);
  }

  return allKeys;
}

const allAccountKeys = await getAllKeys(api, prefix);
console.log(`Total accounts: ${allAccountKeys.length}`);

await api.disconnect();

// Using fetch (HTTP JSON-RPC)
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: 'state_getKeysPaged',
    params: [
      '0x26aa394eea5630e07c48ae0c9558cef7b99d880ec681799c0cf30e8886371da9',
      100
    ],
    id: 1
  })
});

const { result } = await response.json();
console.log(`Found ${result.length} keys`);
```

```python
import requests

def get_keys_paged(prefix, count, start_key=None, block_hash=None):
    params = [prefix, count]
    if start_key:
        params.append(start_key)
    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': 'state_getKeysPaged',
            'params': params,
            'id': 1
        }
    )
    return response.json()['result']

def get_all_keys(prefix, page_size=100):
    """Iterate all storage keys matching a prefix."""
    all_keys = []
    start_key = None

    while True:
        keys = get_keys_paged(prefix, page_size, start_key)
        if not keys:
            break
        all_keys.extend(keys)
        start_key = keys[-1]
        print(f'Fetched {len(all_keys)} keys...')

    return all_keys

# System.Account prefix
prefix = '0x26aa394eea5630e07c48ae0c9558cef7b99d880ec681799c0cf30e8886371da9'
all_keys = get_all_keys(prefix)
print(f'Total account keys: {len(all_keys)}')

# Using substrate-interface
from substrateinterface import SubstrateInterface

substrate = SubstrateInterface(url='wss://api-flop-testnet.n.dwellir.com/YOUR_API_KEY')
keys = substrate.rpc_request('state_getKeysPaged', [prefix, 100])['result']
print(f'First page: {len(keys)} keys')
```

```rust
use serde_json::json;

async fn get_keys_paged(
    client: &reqwest::Client,
    url: &str,
    prefix: &str,
    count: u32,
    start_key: Option<&str>,
) -> Result<Vec<String>, Box<dyn std::error::Error>> {
    let mut params: Vec<serde_json::Value> = vec![
        json!(prefix),
        json!(count),
    ];
    if let Some(key) = start_key {
        params.push(json!(key));
    }

    let response = client
        .post(url)
        .json(&json!({
            "jsonrpc": "2.0",
            "method": "state_getKeysPaged",
            "params": params,
            "id": 1
        }))
        .send()
        .await?;

    let result: serde_json::Value = response.json().await?;
    let keys: Vec<String> = result["result"]
        .as_array()
        .unwrap()
        .iter()
        .map(|v| v.as_str().unwrap().to_string())
        .collect();

    Ok(keys)
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = reqwest::Client::new();
    let url = "https://api-flop-testnet.n.dwellir.com/YOUR_API_KEY";
    let prefix = "0x26aa394eea5630e07c48ae0c9558cef7b99d880ec681799c0cf30e8886371da9";

    // Paginate through all keys
    let mut all_keys = Vec::new();
    let mut start_key: Option<String> = None;

    loop {
        let keys = get_keys_paged(
            &client, url, prefix, 100,
            start_key.as_deref()
        ).await?;

        if keys.is_empty() { break; }
        start_key = Some(keys.last().unwrap().clone());
        all_keys.extend(keys);
        println!("Fetched {} keys...", all_keys.len());
    }

    println!("Total keys: {}", all_keys.len());
    Ok(())
}
```

## Common Use Cases

### 1. Enumerate All Accounts

List all accounts with on-chain state and fetch their balances:

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

async function enumerateAccounts(api, pageSize = 200) {
  const prefix = api.query.system.account.keyPrefix();
  const allKeys = [];
  let startKey;

  // Paginate through all account keys
  while (true) {
    const keys = await api.rpc.state.getKeysPaged(prefix, pageSize, startKey);
    if (keys.length === 0) break;
    allKeys.push(...keys);
    startKey = keys[keys.length - 1];
  }

  console.log(`Found ${allKeys.length} accounts`);

  // Fetch balances in batches using queryStorageAt
  const batchSize = 100;
  for (let i = 0; i < allKeys.length; i += batchSize) {
    const batch = allKeys.slice(i, i + batchSize);
    const results = await api.rpc.state.queryStorageAt(batch);

    results[0].changes.forEach(([key, value]) => {
      if (value) {
        const accountInfo = api.createType('AccountInfo', value);
        console.log(`  Free: ${accountInfo.data.free.toHuman()}`);
      }
    });
  }
}
```

### 2. Export Storage Map for Analysis

Export all entries of a specific storage map for offline analysis:

```javascript
async function exportStorageMap(api, palletName, storageName) {
  const prefix = api.query[palletName][storageName].keyPrefix();
  const entries = [];
  let startKey;

  while (true) {
    const keys = await api.rpc.state.getKeysPaged(prefix, 500, startKey);
    if (keys.length === 0) break;

    const values = await api.rpc.state.queryStorageAt(keys);

    for (const [key, value] of values[0].changes) {
      entries.push({
        key: key.toHex(),
        value: value ? value.toHex() : null
      });
    }

    startKey = keys[keys.length - 1];
    console.log(`Exported ${entries.length} entries...`);
  }

  return entries;
}

// Export all System.Account entries
const accounts = await exportStorageMap(api, 'system', 'account');
```

### 3. Count Storage Items by Prefix

Get a count of entries in any storage map without fetching values:

```javascript
async function countStorageKeys(api, prefix) {
  let count = 0;
  let startKey;

  while (true) {
    const keys = await api.rpc.state.getKeysPaged(prefix, 1000, startKey);
    if (keys.length === 0) break;
    count += keys.length;
    startKey = keys[keys.length - 1];
  }

  return count;
}

// Count total accounts
const accountPrefix = api.query.system.account.keyPrefix();
const totalAccounts = await countStorageKeys(api, accountPrefix);
console.log(`Total accounts on chain: ${totalAccounts}`);
```

ze or add delays between pagination requests |
\| State pruned | Historical state unavailable | Use an archive node for queries at old block hashes |
\| Timeout | Response too slow | Reduce `count` parameter (try 100 instead of 1000) |

## Related Methods

- [`state_getStorage`](https://www.dwellir.com/docs/flop/state_getStorage) -- Get the value for a specific storage key
- [`state_queryStorageAt`](https://www.dwellir.com/docs/flop/state_queryStorageAt) -- Batch query multiple storage keys at once
- [`state_call`](https://www.dwellir.com/docs/flop/state_call) -- Call a runtime API function
- [`state_getMetadata`](https://www.dwellir.com/docs/flop/state_getMetadata) -- Get runtime metadata to determine storage key prefixes
