# beefy_getFinalizedHead - Moonbeam RPC Method

Returns the block hash of the latest BEEFY-finalized block on Moonbeam. BEEFY (Bridge Efficiency Enabling Finality Yielder) provides additional finality proofs that are optimized for light clients and cross-chain bridges, using compact aggregated signatures instead of full GRANDPA justifications.

> **Why Moonbeam?** Build on the cross-chain connected EVM platform on Polkadot with $65M+ TVL and 100+ projects with full EVM compatibility on Polkadot, native XCM cross-chain messaging, 10K+ TPS, 24% staking APR, and $0.015 transaction costs.

## When to Use This Method

`beefy_getFinalizedHead` is important for cross-chain dApp developers, Polkadot builders, and teams requiring multi-chain interoperability:

- **Cross-Chain Bridges** - Verify finality proofs efficiently for bridge operations on cross-chain DeFi, multi-chain dApps, and Ethereum-to-Polkadot bridging via XCM, Axelar, LayerZero, and Wormhole
- **Light Clients** - Verify finality without downloading full GRANDPA justifications
- **Trustless Bridges** - Generate compact finality proofs that can be verified on external chains
- **Bridge Monitoring** - Track BEEFY finality progress relative to GRANDPA finality

## Best Practices

- BEEFY (Bridge Efficiency Enabling Finality Yielder) protocol secures cross-chain bridge finality
- Returns the hash of the latest BEEFY-finalized block for proof generation
- Use for cross-chain verification rather than regular block finality (use `chain_getFinalizedHead` for that)
- Required for bridge relayers that verify finality across connected chains

## Request Parameters

This method accepts no parameters.

## Request Example

```json
{
  "jsonrpc": "2.0",
  "method": "beefy_getFinalizedHead",
  "params": [],
  "id": 1
}
```

## Response Fields

- `result` (`Hash, required`): Hex-encoded 32-byte hash of the latest BEEFY-finalized block

## Successful Response

```json
{
  "jsonrpc": "2.0",
  "id": 1,
  "result": "0x5d83f9a0c22ef15a5e4e8b7f7b3b0c3a1d6e9f2a4b7c8d0e1f2a3b4c5d6e7f80"
}
```

## Error Responses

### Error Response (BEEFY Not Enabled)

- Code: `-32603`

```json
{
  "jsonrpc": "2.0",
  "id": 1,
  "error": {
    "code": -32603,
    "message": "BEEFY is not enabled on this chain"
  }
}
```

## Code Examples

cURL
JavaScript
Python
Rust

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

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

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

try {
  // Get BEEFY finalized head
  const beefyHead = await api.rpc.beefy.getFinalizedHead();
  console.log('BEEFY finalized:', beefyHead.toHex());

  // Compare with GRANDPA finalized
  const grandpaHead = await api.rpc.chain.getFinalizedHead();
  console.log('GRANDPA finalized:', grandpaHead.toHex());

  // Get block numbers for comparison
  const beefyBlock = await api.rpc.chain.getBlock(beefyHead);
  const grandpaBlock = await api.rpc.chain.getBlock(grandpaHead);

  const beefyNum = beefyBlock.block.header.number.toNumber();
  const grandpaNum = grandpaBlock.block.header.number.toNumber();
  console.log(`BEEFY lag behind GRANDPA: ${grandpaNum - beefyNum} blocks`);
} catch (error) {
  console.error('BEEFY may not be enabled:', error.message);
}

await api.disconnect();
```

```python
import requests

def get_beefy_finalized_head():
    url = 'https://api-moonbeam.n.dwellir.com/YOUR_API_KEY'

    payload = {
        'jsonrpc': '2.0',
        'method': 'beefy_getFinalizedHead',
        'params': [],
        'id': 1
    }

    response = requests.post(url, json=payload)
    result = response.json()

    if 'error' in result:
        raise Exception(f"BEEFY error: {result['error']['message']}")

    return result['result']

def get_grandpa_finalized_head():
    url = 'https://api-moonbeam.n.dwellir.com/YOUR_API_KEY'

    payload = {
        'jsonrpc': '2.0',
        'method': 'chain_getFinalizedHead',
        'params': [],
        'id': 2
    }

    response = requests.post(url, json=payload)
    return response.json()['result']

try:
    beefy_hash = get_beefy_finalized_head()
    grandpa_hash = get_grandpa_finalized_head()
    print(f'BEEFY finalized: {beefy_hash}')
    print(f'GRANDPA finalized: {grandpa_hash}')
except Exception as e:
    print(f'Error: {e}')
```

```rust
use subxt::{OnlineClient, PolkadotConfig};
use serde_json::Value;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let api = OnlineClient::<PolkadotConfig>::from_url(
        "wss://api-moonbeam.n.dwellir.com/YOUR_API_KEY"
    ).await?;

    // Call beefy_getFinalizedHead via raw RPC
    let beefy_head: Value = api.rpc()
        .request("beefy_getFinalizedHead", subxt::rpc_params![])
        .await?;

    println!("BEEFY finalized: {}", beefy_head);

    // Compare with GRANDPA finalized
    let grandpa_head = api.rpc()
        .chain_get_finalized_head()
        .await?;

    println!("GRANDPA finalized: {:?}", grandpa_head);

    Ok(())
}
```

## Common Use Cases

### 1. Bridge Finality Verification

Verify BEEFY finality before relaying messages on a cross-chain bridge:

```javascript
async function verifyBridgeFinality(api, targetBlockHash) {
  const beefyHead = await api.rpc.beefy.getFinalizedHead();
  const beefyBlock = await api.rpc.chain.getBlock(beefyHead);
  const beefyNumber = beefyBlock.block.header.number.toNumber();

  const targetBlock = await api.rpc.chain.getBlock(targetBlockHash);
  const targetNumber = targetBlock.block.header.number.toNumber();

  if (beefyNumber >= targetNumber) {
    console.log(`Block #${targetNumber} has BEEFY finality - safe to relay`);
    return true;
  } else {
    console.log(`Waiting: BEEFY at #${beefyNumber}, target at #${targetNumber}`);
    return false;
  }
}
```

### 2. BEEFY vs GRANDPA Finality Monitor

Track the gap between the two finality gadgets:

```javascript
async function monitorFinalityGadgets(api) {
  setInterval(async () => {
    try {
      const [beefyHead, grandpaHead] = await Promise.all([
        api.rpc.beefy.getFinalizedHead(),
        api.rpc.chain.getFinalizedHead()
      ]);

      const [beefyBlock, grandpaBlock] = await Promise.all([
        api.rpc.chain.getBlock(beefyHead),
        api.rpc.chain.getBlock(grandpaHead)
      ]);

      const beefyNum = beefyBlock.block.header.number.toNumber();
      const grandpaNum = grandpaBlock.block.header.number.toNumber();
      const lag = grandpaNum - beefyNum;

      console.log(`GRANDPA: #${grandpaNum} | BEEFY: #${beefyNum} | Lag: ${lag} blocks`);
    } catch (error) {
      console.error('Monitor error:', error.message);
    }
  }, 12000);
}
```

## BEEFY vs GRANDPA Finality

| Aspect                | GRANDPA                                | BEEFY                                      |
| --------------------- | -------------------------------------- | ------------------------------------------ |
| **Purpose**           | Primary chain finality                 | Bridge-optimized finality                  |
| **Proof Size**        | Larger (full validator set signatures) | Compact (aggregated BLS signatures)        |
| **Latency**           | Immediate after supermajority          | Slightly delayed behind GRANDPA            |
| **Verification Cost** | Higher on external chains              | Lower - designed for on-chain verification |
| **Use Case**          | On-chain consensus finality            | Cross-chain bridges and light clients      |

## Availability

BEEFY is enabled on Polkadot and Kusama relay chains and some parachains. If BEEFY is not active on the chain you are querying, this method will return an error. Check chain documentation or try calling the method to confirm availability.

## Related Methods

- [`chain_getFinalizedHead`](https://www.dwellir.com/docs/moonbeam/chain_getFinalizedHead) - Get GRANDPA finalized head
- [`grandpa_roundState`](https://www.dwellir.com/docs/moonbeam/grandpa_roundState) - Monitor GRANDPA consensus state
- [`chain_subscribeFinalizedHeads`](https://www.dwellir.com/docs/moonbeam/chain_subscribeFinalizedHeads) - Subscribe to GRANDPA finalized blocks
