---
title: FAsset Auto-Redemption
tags: [intermediate, fassets]
slug: fxrp-autoredeem
description: Auto-redeem FAssets to native XRP cross-chain
keywords: [fassets, flare-network, fxrp, layerzero, cross-chain]
---

import CodeBlock from "@theme/CodeBlock";
import FassetRedeemComposer from "!!raw-loader!/examples/developer-hub-solidity/FAssetRedeemComposer.sol";
import bridgeToHyperEVM from "!!raw-loader!/examples/developer-hub-javascript/bridgeToHyperEVM.ts";
import bridgeToHyperCore from "!!raw-loader!/examples/developer-hub-javascript/bridgeToHyperCore.ts";
import autoRedeemFromHyperEVM from "!!raw-loader!/examples/developer-hub-javascript/autoRedeemFromHyperEVM.ts";
import autoRedeemFromHyperCore from "!!raw-loader!/examples/developer-hub-javascript/autoRedeemFromHyperCore.ts";
import getOftPeers from "!!raw-loader!/examples/developer-hub-javascript/getOftPeers.ts";

## Overview

In this guide, you will learn how to bridge FAssets (specifically FXRP) between Flare Testnet Coston2 and Hyperliquid using LayerZero's cross-chain messaging protocol, with support for **automatic redemption** - converting FXRP back to native XRP on the XRP Ledger in a single transaction.

This guide covers four key functionalities:

1. **Bridging FXRP from Flare Testnet Coston2 to Hyperliquid EVM** (`bridgeToHyperEVM.ts`) - Transfer wrapped XRP tokens to Hyperliquid EVM for DeFi use.
2. **Bridging FXRP from Flare Testnet Coston2 to HyperCore** (`bridgeToHyperCore.ts`) - Transfer wrapped XRP tokens directly to HyperCore for spot trading.
3. **Auto-Redeem from Hyperliquid EVM to Underlying Asset** (`autoRedeemFromHyperEVM.ts`) - Send FXRP from Hyperliquid EVM back to Flare Testnet Coston2 and automatically redeem it for native XRP.
4. **Auto-Redeem from HyperCore to Underlying Asset** (`autoRedeemFromHyperCore.ts`) - Transfer FXRP from HyperCore spot wallet to HyperEVM, then automatically bridge and redeem to native XRP in one script.

**Key technologies:**

- [LayerZero OFT](https://docs.layerzero.network/v2/developers/evm/oft/quickstart) (Omnichain Fungible Token) for cross-chain token transfers.
  OFT works by burning tokens on the source chain and minting equivalent tokens on the destination chain, enabling seamless movement of assets across different blockchains.
- Flare's [FAsset](/fassets/overview) system for tokenizing non-smart contract assets.
- [LayerZero Composer](https://docs.layerzero.network/v2/developers/evm/oft/composing) pattern for executing custom logic (like FAsset redemption) automatically when tokens arrive on the destination chain.
- [Hyperliquid spotSend API](https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/exchange-endpoint#spot-transfer) for transferring tokens between HyperCore and HyperEVM.

This guide includes a Solidity smart contract (`FAssetRedeemComposer.sol`) and four TypeScript scripts (`bridgeToHyperEVM.ts`, `bridgeToHyperCore.ts`, `autoRedeemFromHyperEVM.ts`, and `autoRedeemFromHyperCore.ts`) that demonstrate the complete workflows.

Clone the [Flare Hardhat Starter](https://github.com/flare-foundation/flare-hardhat-starter) to follow along.

## Getting Started: The Two-Step Process

:::warning

To successfully test the auto-redemption feature, you must run the scripts in the correct order.
You must complete [Step 1](#step-1-bridge-fxrp-to-hyperliquid-evm-required-first) (bridging TO Hyperliquid) before you can execute [Step 2](#step-2-auto-redeem-to-native-xrp-requires-step-1) (auto-redeeming FROM Hyperliquid).

:::

### Step 1: Bridge FXRP to Hyperliquid EVM (Required First)

Run [`bridgeToHyperEVM.ts`](https://github.com/flare-foundation/flare-hardhat-starter/blob/main/scripts/fassets/bridgeToHyperEVM.ts) on **Flare Testnet Coston2** network to transfer your FXRP tokens from Coston2 to Hyperliquid EVM Testnet.
This script does NOT involve auto-redemption - it simply moves your tokens to Hyperliquid where you can use them to prepare for the auto-redemption process.

:::info

You need FXRP tokens on Hyperliquid EVM before you can test the auto-redeem functionality.
The auto-redeem script will fail if you don't have tokens there.

:::

```bash
# Step 1: Bridge tokens TO Hyperliquid
yarn hardhat run scripts/fassets/bridgeToHyperEVM.ts --network coston2
```

### Step 2: Auto-Redeem to Native XRP (Requires Step 1)

Once you have FXRP tokens on Hyperliquid (from Step 1), run [`autoRedeemFromHyperEVM.ts`](https://github.com/flare-foundation/flare-hardhat-starter/blob/main/scripts/fassets/autoRedeemFromHyperEVM.ts) on **Hyperliquid Testnet** network to send them back to Flare Testnet Coston2 with automatic redemption to native XRP.
This is the auto-redemption feature that converts FXRP back to native XRP on the XRP Ledger in a single transaction.

```bash
# Step 2: Auto-redeem back to native XRP
yarn hardhat run scripts/fassets/autoRedeemFromHyperEVM.ts --network hyperliquidTestnet
```

## FAssetRedeemComposer Contract

### What It Is

`FAssetRedeemComposer.sol` is a LayerZero Composer contract that automatically redeems FAssets to their underlying assets when tokens arrive on Flare Testnet Coston2 via LayerZero's compose message feature.

### How It Works

The composer implements the [IOAppComposer](https://docs.layerzero.network/v2/developers/evm/composer/overview) interface and processes LayerZero compose messages:

1. **Receives Compose Message**: LayerZero endpoint calls [lzCompose()](https://docs.layerzero.network/v2/developers/evm/composer/overview#:~:text=/**%0A%20%20%20%20%20*%20%40notice%20Handles,messages%0A%20%20%20%20%7D%0A%7D) with the incoming OFT transfer and compose data.
2. **Extracts Parameters**: Decodes the compose message to get:
   - Amount to redeem (in lots).
   - Underlying XRP address on the XRP Ledger.
   - Redeemer EVM address on Flare Chain.
3. **Gets Asset Manager**: Retrieves the FAsset AssetManager from Flare's ContractRegistry.
4. **Calculates Lots**: Determines how many lots can be redeemed based on received balance.
5. **Approves Tokens**: Grants AssetManager permission to spend the FAsset tokens (which is in the [ERC-20](https://eips.ethereum.org/EIPS/eip-20) standard).
6. **Executes Redemption**: Calls [`assetManager.redeem()`](/fassets/reference/IAssetManager#redeem) to burn FAssets and release underlying XRP.

<CodeBlock language="solidity" title="contracts/FAssetRedeemComposer.sol">
  {FassetRedeemComposer}
</CodeBlock>

### Code Breakdown

The `_processRedemption` function contains the core redemption logic with numbered steps in the comments:

1. **Decode Message**: Extracts the underlying XRP address and redeemer EVM address from the compose message.
2. **Get Asset Manager & fXRP Token**: Retrieves the FAsset AssetManager.
3. **Check Balance**: Verifies that tokens were received from LayerZero. Reverts with `InsufficientBalance()` if balance is zero.
4. **Calculate Lots**: Determines how many complete lots can be redeemed based on the received balance and the lot size from AssetManager settings.
5. **Calculate Amount**: Computes the exact amount to redeem (must be a multiple of lot size). Reverts with `AmountTooSmall()` if less than 1 lot.
6. **Approve AssetManager**: Grants the AssetManager permission to spend the FAsset tokens using the ERC-20 `approve` pattern.
7. **Redeem**: Calls [`assetManager.redeem()`](/fassets/reference/IAssetManager#redeem) to burn FAssets and trigger the release of underlying XRP to the specified address.

The contract also includes `recoverTokens()` and `recoverNative()` helper functions that allow the owner to recover any stuck tokens or native currency if needed.

## Bridge FXRP to Hyperliquid EVM (Step 1)

### What It Is

**This is Step 1 of the two-step process** and is a **prerequisite** for testing the auto-redemption feature.

This script bridges FXRP tokens from Flare Testnet Coston2 to Hyperliquid EVM Testnet using LayerZero's OFT Adapter pattern.
It wraps existing ERC20 FAsset tokens into LayerZero OFT format for cross-chain transfer.

:::warning

This script does NOT perform auto-redemption.

:::
Its purpose is to get your FXRP tokens onto Hyperliquid EVM Testnet so that:

- You can use them for trading or DeFi on Hyperliquid, OR
- You can run the auto-redeem script (Step 2) to convert them back to native XRP

You must successfully complete this step before running the `autoRedeemFromHyperEVM.ts` script.

### How It Works

#### Step-by-Step Process

1. **Get Asset Manager Info**: Retrieves fAsset address and lot size dynamically from the AssetManager contract using the `getAssetManagerFXRP` utility.
2. **Balance Check**: Verifies user has sufficient FTestXRP tokens.
3. **Token Approval**:
   - Approves OFT Adapter to spend FTestXRP.
   - Approves Composer (if needed for future operations).
4. **Build Send Parameters**:
   - Destination: Hyperliquid EVM Testnet (EndpointID for Hyperliquid Testnet: `40294`).
   - Recipient: Same address on destination chain.
   - Amount: Calculated from configured lots (default 1 lot, with 10% buffer for safety).
   - LayerZero options: Executor gas limit set to 200,000.
5. **Quote Fee**: Calculates the LayerZero cross-chain messaging fee.
6. **Execute Bridge**: Sends tokens via `oftAdapter.send()`.
7. **Confirmation**: Waits for transaction confirmation and provides tracking link to the LayerZero Explorer page.

### Prerequisites

- **Balance Requirements**:
  - FTestXRP tokens (amount you want to bridge).
  - C2FLR tokens (for gas fees + LayerZero fees).
    You can get some from the Flare Testnet [faucet](https://faucet.flare.network/).
- **Environment Setup**:
  - Private key configured in Hardhat for Flare Testnet Coston2 and Hyperliquid Testnet.

### Configuration

Edit the `CONFIG` object in the script:

```typescript
const CONFIG = {
  COSTON2_OFT_ADAPTER: "0xCd3d2127935Ae82Af54Fc31cCD9D3440dbF46639",
  COSTON2_COMPOSER: process.env.COSTON2_COMPOSER || "",
  HYPERLIQUID_EID: EndpointId.HYPERLIQUID_V2_TESTNET,
  EXECUTOR_GAS: 200_000,
  BRIDGE_LOTS: "1", // Change this to your desired number of lots
};
```

### How to Run

**Run this script FIRST before attempting auto-redemption.**
This gets your FXRP tokens onto Hyperliquid EVM.

1. **Install Dependencies**:

   ```bash
   yarn install
   ```

2. **Configure Environment**:

   ```bash
   # .env file
   COSTON2_RPC_URL=https://coston2-api.flare.network/ext/C/rpc
   DEPLOYER_PRIVATE_KEY=your_private_key_here
   COSTON2_COMPOSER=0x... # Optional for this step, required for Step 2
   ```

3. **Run the Script on Flare Testnet Coston2**:

   ```bash
   yarn hardhat run scripts/fassets/bridgeToHyperEVM.ts --network coston2
   ```

4. **Wait for Completion**:
   - Monitor the transaction on LayerZero Scan (link provided in output)
   - Allow 2-5 minutes for cross-chain delivery
   - Verify FXRP balance increased on Hyperliquid EVM before proceeding to Step 2

### Expected Output

```
Using account: 0x742d35Cc6634C0532925a3b844Bc454e4438f44e

📋 Bridge Details:
From: Coston2
To: Hyperliquid EVM Testnet
Amount: 11.0 FXRP
Recipient: 0x742d35Cc6634C0532925a3b844Bc454e4438f44e

Your FTestXRP balance: 100.0

1️⃣ Checking OFT Adapter token address...
   OFT Adapter's inner token: 0x8b4abA9C4BD7DD961659b02129beE20c6286e17F
   Expected token: 0x8b4abA9C4BD7DD961659b02129beE20c6286e17F
   Match: true

   Approving FTestXRP for OFT Adapter...
   OFT Adapter address: 0xCd3d2127935Ae82Af54Fc31cCD9D3440dbF46639
   Amount: 11.0 FXRP
✅ OFT Adapter approved
   Verified allowance: 22.0 FXRP

3️⃣ LayerZero Fee: 0.001234 C2FLR

4️⃣ Sending FXRP to Hyperliquid EVM Testnet...
Transaction sent: 0xabc123...
✅ Confirmed in block: 12345678

🎉 Success! Your FXRP is on the way to Hyperliquid EVM Testnet!

Track your transaction:
https://testnet.layerzeroscan.com/tx/0xabc123...

It may take a few minutes to arrive on Hyperliquid EVM Testnet.
```

<details>
<summary>View `bridgeToHyperEVM.ts` source code</summary>

<CodeBlock language="typescript" title="scripts/fassets/bridgeToHyperEVM.ts">
  {bridgeToHyperEVM}
</CodeBlock>

</details>

### Troubleshooting

**Error: Insufficient FTestXRP balance**

- Solution: Acquire FTestXRP tokens on Flare Testnet Coston2 [faucet](https://faucet.flare.network/coston2) or follow our Fasset minting [guide](/fassets/developer-guides/fassets-mint).

**Error: Insufficient C2FLR for gas**

- Solution: Get C2FLR from Flare Testnet Coston2 [faucet](https://faucet.flare.network/coston2).

**Error: Transaction reverted**

- Check that the OFT Adapter address matches the FTestXRP token.
- Verify LayerZero endpoint is operational.
- Ensure gas limits are sufficient.

## Bridge FXRP to HyperCore

### What It Is

This script bridges FXRP tokens from Flare Testnet Coston2 directly to Hyperliquid HyperCore (the spot trading layer) using LayerZero's OFT Adapter with a compose message.
Unlike `bridgeToHyperEVM.ts` which deposits tokens on HyperEVM, this script triggers automatic transfer to HyperCore where you can trade FXRP on Hyperliquid's spot market.

:::info Understanding the Difference

- **bridgeToHyperEVM.ts**: Deposits FXRP on HyperEVM (EVM layer) for DeFi use.
- **bridgeToHyperCore.ts**: Deposits FXRP on HyperCore (trading layer) for spot trading.

Choose based on whether you want to use FXRP in smart contracts (HyperEVM) or trade it (HyperCore).

:::

### How It Works

#### Flow Diagram

```
┌─────────────────────────┐
│   Developer             │
│   (Coston2)             │
└────────┬────────────────┘
         │
         │ 1. Has FXRP tokens
         ▼
┌─────────────────────────┐
│  FXRP (Coston2)         │
│  Balance: 11 FXRP       │
└────────┬────────────────┘
         │
         │ 2. Send via OFT Adapter
         │    with Compose Message
         ▼
┌─────────────────────────┐
│  LayerZero Endpoint     │
│  - lzSend()             │
│  - Compose enabled      │
└────────┬────────────────┘
         │
         │ 3. Cross-chain message
         ▼
┌─────────────────────────┐
│  HyperEVM Endpoint      │
│  - lzReceive()          │
│  - lzCompose()          │
└────────┬────────────────┘
         │
         │ 4. Calls Composer
         ▼
┌─────────────────────────┐
│ HyperliquidComposer     │
│  - Receives FXRP        │
│  - Transfers to system  │
│    address              │
└────────┬────────────────┘
         │
         │ 5. HyperCore credit
         ▼
┌─────────────────────────┐
│  HyperCore Spot Wallet  │
│  FXRP credited          │
└─────────────────────────┘
```

#### Step-by-Step Process

1. **Validate Config**: Checks that `HYPERLIQUID_COMPOSER` is configured.
2. **Get Asset Manager Info**: Retrieves fAsset address and lot size dynamically from the AssetManager contract.
3. **Balance Check**: Verifies user has sufficient FTestXRP tokens.
4. **Token Approval**: Approves OFT Adapter to spend FTestXRP.
5. **Encode Compose Message**: Encodes `(uint256 amount, address recipient)` for HyperCore transfer.
6. **Build LayerZero Options**:
   - Executor gas for `lzReceive()`: 200,000
   - Compose gas for `lzCompose()`: 300,000
7. **Build Send Parameters**:
   - Destination: HyperEVM (EndpointID for Hyperliquid Testnet: `40294`).
   - Recipient: HyperliquidComposer contract (not user address).
   - Amount: Calculated from configured lots (default 1 lot, with 10% buffer).
8. **Quote Fee**: Calculates the LayerZero cross-chain messaging fee.
9. **Execute Bridge**: Sends tokens via `oftAdapter.send()` with compose.
10. **HyperCore Credit**: Upon arrival, composer transfers tokens to HyperCore.

### Prerequisites

- **Balance Requirements**:
  - FTestXRP tokens on Coston2 (amount you want to bridge).
  - C2FLR tokens (for gas fees + LayerZero fees).
    You can get some from the Flare Testnet [faucet](https://faucet.flare.network/).
- **Deployed Contracts**:
  - HyperliquidComposer must be deployed on HyperEVM Testnet.
  - Composer address must be set in `.env`.

### Configuration

Edit the `CONFIG` object in the script:

```typescript
const CONFIG = {
  COSTON2_OFT_ADAPTER: "0xCd3d2127935Ae82Af54Fc31cCD9D3440dbF46639",
  HYPERLIQUID_COMPOSER: process.env.HYPERLIQUID_COMPOSER || "",
  HYPERLIQUID_EID: EndpointId.HYPERLIQUID_V2_TESTNET,
  EXECUTOR_GAS: 200_000, // Gas for receiving on HyperEVM
  COMPOSE_GAS: 300_000, // Gas for compose execution
  BRIDGE_LOTS: "1", // Change this to your desired number of lots
};
```

### How to Run

1. **Deploy HyperliquidComposer** (first time only):

   ```bash
   yarn hardhat run scripts/fassets/deployHyperliquidComposer.ts --network hyperliquidTestnet
   ```

2. **Configure Environment**:

   ```bash
   # .env file
   COSTON2_RPC_URL=https://coston2-api.flare.network/ext/C/rpc
   DEPLOYER_PRIVATE_KEY=your_private_key_here
   HYPERLIQUID_COMPOSER=0x... # Required! Set this after deploying the composer
   ```

3. **Run the Script on Flare Testnet Coston2**:

   ```bash
   yarn hardhat run scripts/fassets/bridgeToHyperCore.ts --network coston2
   ```

4. **Wait for Completion**:
   - Monitor the transaction on LayerZero Scan (link provided in output).
   - Allow 2-5 minutes for cross-chain delivery.
   - Verify FXRP balance on HyperCore via Hyperliquid's UI or API.

### Expected Output

```
✓ HyperliquidComposer configured: 0x123...
Using account: 0x742d35Cc6634C0532925a3b844Bc454e4438f44e
Token address: 0x8b4abA9C4BD7DD961659b02129beE20c6286e17F
Token decimals: 6

📋 Bridge Details:
From: Coston2
To: Hyperliquid HyperCore (via HyperEVM)
Amount: 11.0 FXRP
HyperCore Recipient: 0x742d35Cc6634C0532925a3b844Bc454e4438f44e

Your FTestXRP balance: 100.0

1️⃣ Checking OFT Adapter token address...
   OFT Adapter's underlying token: 0x8b4abA9C4BD7DD961659b02129beE20c6286e17F
   Expected token: 0x8b4abA9C4BD7DD961659b02129beE20c6286e17F
   Match: true

   Approving FTestXRP for OFT Adapter...
   OFT Adapter address: 0xCd3d2127935Ae82Af54Fc31cCD9D3440dbF46639
   Amount: 11.0 FXRP
✅ OFT Adapter approved
   Verified allowance: 11.0 FXRP

2️⃣ Compose message encoded for HyperCore transfer

3️⃣ LayerZero Fee: 0.001234 C2FLR

4️⃣ Sending FXRP to Hyperliquid HyperCore...
   Via HyperliquidComposer: 0x123...
Transaction sent: 0xabc123...
✅ Confirmed in block: 12345678

🎉 Success! Your FXRP is on the way to Hyperliquid HyperCore!

Track your transaction:
https://testnet.layerzeroscan.com/tx/0xabc123...

⏳ The tokens will be automatically transferred to HyperCore once they arrive on HyperEVM.
You can then trade them on the Hyperliquid DEX.
```

<details>
<summary>View `bridgeToHyperCore.ts` source code</summary>

<CodeBlock language="typescript" title="scripts/fassets/bridgeToHyperCore.ts">
  {bridgeToHyperCore}
</CodeBlock>

</details>

### Troubleshooting

**Error: HYPERLIQUID_COMPOSER not set**

- Solution: Deploy the HyperliquidComposer contract on HyperEVM Testnet first.

**Error: Insufficient FTestXRP balance**

- Solution: Acquire FTestXRP tokens on Flare Testnet Coston2 [faucet](https://faucet.flare.network/coston2) or follow our Fasset minting [guide](/fassets/developer-guides/fassets-mint).

**Error: Insufficient C2FLR for gas**

- Solution: Get C2FLR from Flare Testnet Coston2 [faucet](https://faucet.flare.network/coston2).

**Error: Tokens arrived on HyperEVM but not on HyperCore**

- Check that the HyperliquidComposer is correctly configured.
- Verify the compose message was properly encoded.
- Check LayerZero Scan for compose execution status.

## Auto-Redeem from Hyperliquid EVM (Step 2)

### What It Is

**This is Step 2 of the two-step process** and **requires you to have FXRP tokens on Hyperliquid EVM first** (from [Step 1](#step-1-bridge-fxrp-to-hyperliquid-evm-required-first)).

This script sends FXRP from Hyperliquid EVM Testnet back to Flare Testnet Coston2 with **automatic redemption** to native XRP on the XRP Ledger.
It uses LayerZero's compose feature to trigger the `FAssetRedeemComposer` contract upon arrival.

**Prerequisites:**

- You must have FXRP OFT tokens on Hyperliquid EVM Testnet.
- If you don't have FXRP on Hyperliquid, run `bridgeToHyperEVM.ts` first ([Step 1](#step-1-bridge-fxrp-to-hyperliquid-evm-required-first)).
- The FAssetRedeemComposer contract must be deployed on Flare Testnet Coston2.

### How It Works

#### Flow Diagram

```
┌──────────────────┐
│   Developer      │
│ (Hyperliquid EVM)│
└────────┬─────────┘
         │
         │ 1. Has FXRP OFT
         ▼
┌─────────────────────────┐
│  FXRP OFT (Hyperliquid) │
│  Balance: 10 FXRP       │
└────────┬────────────────┘
         │
         │ 2. Send with Compose Message
         │    - Destination: Coston2 Composer
         │    - Compose Data: (amount, xrpAddress, redeemer)
         ▼
┌─────────────────────────┐
│  LayerZero Endpoint     │
│  - lzSend()             │
│  - Compose enabled      │
└────────┬────────────────┘
         │
         │ 3. Cross-chain message
         ▼
┌─────────────────────────┐
│  Coston2 Endpoint       │
│  - lzReceive()          │
│  - lzCompose()          │
└────────┬────────────────┘
         │
         │ 4. Calls Composer
         ▼
┌─────────────────────────┐
│ FAssetRedeemComposer    │
│  - Receives FXRP        │
│  - Calculates lots      │
│  - Calls AssetManager   │
└────────┬────────────────┘
         │
         │ 5. Redemption
         ▼
┌─────────────────────────┐
│  FAsset AssetManager    │
│  - Burns FXRP           │
│  - Releases XRP         │
└────────┬────────────────┘
         │
         │ 6. XRP sent to address
         ▼
┌─────────────────────────┐
│  XRP Ledger Address     │
│  rpHuw4b...             │
└─────────────────────────┘
```

#### Step-by-Step Process

1. **Validate Setup**:
   - Checks that `COSTON2_COMPOSER` is configured.
   - Gets the signer account.
2. **Connect to FXRP OFT**: Gets the OFT contract on Hyperliquid using the `FXRPOFT` artifact.
3. **Prepare Redemption Parameters**:
   - Number of lots to send (default: 1 lot, amount calculated using `calculateAmountToSend` utility).
   - XRP address to receive native XRP.
   - Redeemer address (EVM address).
4. **Encode Compose Message**:
   - Encodes `(uint256 amount, string xrpAddress, address redeemer)`.
   - This tells the composer what to do when tokens arrive.
5. **Build LayerZero Options**:
   - Executor gas for `lzReceive()`: 1,000,000
   - Compose gas for `lzCompose()`: 1,000,000
6. **Build Send Parameters**:
   - Destination: Coston2 (Endpoint ID: `40296`).
   - Recipient: FAssetRedeemComposer contract.
   - Amount: Calculated from configured lots (default 1 lot).
   - Compose message included
7. **Check Balance**: Verifies user has sufficient FXRP OFT.
8. **Quote Fee**: Calculates LayerZero messaging fee.
9. **Execute Send**: Sends FXRP with compose message.
10. **Auto-Redemption**: On arrival, composer automatically redeems to XRP.

### Prerequisites

- **Network**: Must run on Hyperliquid EVM Testnet.
- **Balance Requirements**:
  - FXRP OFT tokens on Hyperliquid (amount you want to redeem).
  - HYPE tokens (for gas fees + LayerZero fees).
- **Deployed Contracts**:
  - FAssetRedeemComposer must be deployed on Flare Testnet Coston2.
  - Composer address must be set in `.env`.

### Configuration

Edit the `CONFIG` object in the script:

```typescript
const CONFIG = {
  HYPERLIQUID_FXRP_OFT:
    process.env.HYPERLIQUID_FXRP_OFT ||
    "0x14bfb521e318fc3d5e92A8462C65079BC7d4284c",
  COSTON2_COMPOSER:
    process.env.COSTON2_COMPOSER ||
    "0x5051E8db650E9e0E2a3f03010Ee5c60e79CF583E",
  COSTON2_EID: EndpointId.FLARE_V2_TESTNET,
  EXECUTOR_GAS: 1_000_000, // Gas for receiving on Coston2
  COMPOSE_GAS: 1_000_000, // Gas for compose execution
  SEND_LOTS: "1", // Number of lots to redeem
  XRP_ADDRESS: "rpHuw4bKSjonKRrKKVYYVedg1jyPrmp", // Your XRP address
};
```

### How to Run

**PREREQUISITE: You must have FXRP tokens on Hyperliquid EVM Testnet before running this script.**

If you don't have FXRP on Hyperliquid yet:

- Run `bridgeToHyperEVM.ts` first ([Step 1](#step-1-bridge-fxrp-to-hyperliquid-evm-required-first))
- Wait for the bridge transaction to complete (2-5 minutes)
- Verify your FXRP balance on Hyperliquid EVM before proceeding

Once you have FXRP on Hyperliquid:

1. **Deploy FAssetRedeemComposer** (first time only):

   ```bash
   npx hardhat deploy --network coston2 --tags FAssetRedeemComposer
   ```

2. **Configure Environment**:

   ```bash
   # .env file
   HYPERLIQUID_TESTNET_RPC_URL=https://api.hyperliquid-testnet.xyz/evm
   DEPLOYER_PRIVATE_KEY=your_private_key_here
   COSTON2_COMPOSER=0x... # Required! Set this after deploying the composer
   HYPERLIQUID_FXRP_OFT=0x14bfb521e318fc3d5e92A8462C65079BC7d4284c
   ```

3. **Update XRP Address**:
   - Edit `CONFIG.XRP_ADDRESS` in the script to your XRP ledger address
   - This is where you'll receive the native XRP
   - Must be a valid XRP address format (starts with 'r')

4. **Run the Script on Hyperliquid Testnet**:
   ```bash
   yarn hardhat run scripts/fassets/autoRedeemFromHyperEVM.ts --network hyperliquidTestnet
   ```

### Expected Output

```
Using account: 0x742d35Cc6634C0532925a3b844Bc454e4438f44e
✓ Composer configured: 0x123...

📋 Redemption Parameters:
Amount: 10.0 FXRP
XRP Address: rpHuw4bKSjonKRrKKVYYVedg1jyPrmp
Redeemer: 0x742d35Cc6634C0532925a3b844Bc454e4438f44e

Connecting to FXRP OFT on Hyperliquid EVM: 0x14bfb521e318fc3d5e92A8462C65079BC7d4284c

✓ Connected to FXRP OFT: 0x14bfb521e318fc3d5e92A8462C65079BC7d4284c
OFT address: 0x14bfb521e318fc3d5e92A8462C65079BC7d4284c

Compose message encoded

💰 Current FXRP balance: 25.0
Sufficient balance

💵 LayerZero Fee: 0.002456 HYPE

🚀 Sending 10.0 FXRP to Coston2 with auto-redeem...
Target composer: 0x123...
Underlying address: rpHuw4bKSjonKRrKKVYYVedg1jyPrmp

✓ Transaction sent: 0xdef456...
Waiting for confirmation...
✅ Confirmed in block: 9876543

🎉 Success! Your FXRP is on the way to Coston2!

📊 Track your cross-chain transaction:
https://testnet.layerzeroscan.com/tx/0xdef456...

⏳ The auto-redeem will execute once the message arrives on Coston2.
XRP will be sent to: rpHuw4bKSjonKRrKKVYYVedg1jyPrmp
```

<details>
<summary>View `autoRedeemFromHyperEVM.ts` source code</summary>

<CodeBlock
  language="typescript"
  title="scripts/fassets/autoRedeemFromHyperEVM.ts"
>
  {autoRedeemFromHyperEVM}
</CodeBlock>

</details>

## Auto-Redeem from HyperCore

### What It Is

This script provides a complete auto-redemption flow starting from HyperCore (Hyperliquid's spot trading layer) to native XRP on the XRP Ledger.
Unlike the HyperEVM flow which assumes you already have FXRP on HyperEVM, this script handles the full journey: **HyperCore → HyperEVM → Coston2 → XRP Ledger**.

:::info Understanding HyperCore vs HyperEVM

**HyperCore** is Hyperliquid's high-performance spot trading layer where tokens are held in spot wallets.
**HyperEVM** is Hyperliquid's EVM-compatible execution environment where tokens exist as ERC-20s.
Tokens must be transferred from HyperCore to HyperEVM before they can be bridged via LayerZero.

:::

**Prerequisites:**

- You must have FXRP tokens in your HyperCore spot wallet.
- You need HYPE tokens on HyperEVM for LayerZero fees.
- The FAssetRedeemComposer contract must be deployed on Flare Testnet Coston2.

### How It Works

#### Flow Diagram

```
┌─────────────────────────┐
│   Developer             │
│   (HyperCore Spot)      │
└────────┬────────────────┘
         │
         │ 1. Has FXRP in spot wallet
         ▼
┌─────────────────────────┐
│  HyperCore Spot Wallet  │
│  Balance: 10 FXRP       │
└────────┬────────────────┘
         │
         │ 2. spotSend to system address
         │    (EIP-712 signed)
         ▼
┌─────────────────────────┐
│  Hyperliquid API        │
│  - /exchange endpoint   │
│  - spotSend action      │
└────────┬────────────────┘
         │
         │ 3. Tokens appear on HyperEVM
         ▼
┌─────────────────────────┐
│  FXRP OFT (HyperEVM)    │
│  Balance: 10 FXRP       │
└────────┬────────────────┘
         │
         │ 4. Send with Compose Message
         │    - Destination: Coston2 Composer
         │    - Compose Data: (amount, xrpAddress, redeemer)
         ▼
┌─────────────────────────┐
│  LayerZero Endpoint     │
│  - lzSend()             │
│  - Compose enabled      │
└────────┬────────────────┘
         │
         │ 5. Cross-chain message
         ▼
┌─────────────────────────┐
│  Coston2 Endpoint       │
│  - lzReceive()          │
│  - lzCompose()          │
└────────┬────────────────┘
         │
         │ 6. Calls Composer
         ▼
┌─────────────────────────┐
│ FAssetRedeemComposer    │
│  - Receives FXRP        │
│  - Calculates lots      │
│  - Calls AssetManager   │
└────────┬────────────────┘
         │
         │ 7. Redemption
         ▼
┌─────────────────────────┐
│  FAsset AssetManager    │
│  - Burns FXRP           │
│  - Releases XRP         │
└────────┬────────────────┘
         │
         │ 8. XRP sent to address
         ▼
┌─────────────────────────┐
│  XRP Ledger Address     │
│  rpHuw4b...             │
└─────────────────────────┘
```

#### Step-by-Step Process

1. **Validate Setup**:
   - Checks that `COSTON2_COMPOSER` is configured.
   - Gets the signer account.
2. **Check HyperCore Balance**:
   - Queries HyperCore spot balance via the `/info` API endpoint.
   - Verifies sufficient FXRP is available.
3. **Transfer from HyperCore to HyperEVM**:
   - Prepares an EIP-712 signed `spotSend` message.
   - Sends to the FXRP system address (`0x20000000000000000000000000000000000005a3`).
   - Waits for the transfer to settle on HyperEVM.
4. **Connect to FXRP OFT**: Gets the OFT contract on HyperEVM.
5. **Prepare Redemption Parameters**:
   - Number of lots to send (default: 1 lot).
   - XRP address to receive native XRP.
   - Redeemer address (EVM address).
6. **Check HyperEVM Balance**: Verifies tokens arrived from HyperCore.
7. **Encode Compose Message**:
   - Encodes `(uint256 amount, string xrpAddress, address redeemer)`.
   - This tells the composer what to do when tokens arrive.
8. **Build LayerZero Options**:
   - Executor gas for `lzReceive()`: 1,000,000
   - Compose gas for `lzCompose()`: 1,000,000
9. **Quote Fee**: Calculates LayerZero messaging fee.
10. **Execute Send**: Sends FXRP with compose message to Coston2.
11. **Auto-Redemption**: On arrival, composer automatically redeems to XRP.

### Understanding HyperCore Transfers

The script uses Hyperliquid's `spotSend` API to transfer tokens from HyperCore to HyperEVM.
This requires EIP-712 signing with specific parameters.

#### EIP-712 Domain

```typescript
const EIP712_DOMAIN = {
  name: "HyperliquidSignTransaction",
  version: "1",
  chainId: 42161, // Arbitrum chainId - required by Hyperliquid API
  verifyingContract: "0x0000000000000000000000000000000000000000",
};
```

:::warning Arbitrum ChainId Requirement

Hyperliquid's API requires Arbitrum's chainId (42161) for all EIP-712 signatures, regardless of the actual chain.
This is a legacy requirement from when Hyperliquid settled on Arbitrum.

:::

#### System Address

To transfer tokens from HyperCore to HyperEVM, you send them to a special system address.
Each token has a unique system address based on its token index.

```typescript
// System address for FXRP on testnet (token index 1443 = 0x5A3)
FXRP_SYSTEM_ADDRESS: "0x20000000000000000000000000000000000005a3";
```

### Prerequisites

- **Network**: Must run on Hyperliquid EVM Testnet.
- **Balance Requirements**:
  - FXRP tokens in your HyperCore spot wallet (amount you want to redeem).
  - HYPE tokens on HyperEVM (for gas fees + LayerZero fees).
- **Deployed Contracts**:
  - FAssetRedeemComposer must be deployed on Flare Testnet Coston2.
  - Composer address must be set in `.env`.

### Configuration

Edit the `CONFIG` object in the script:

```typescript
const CONFIG = {
  // Testnet config
  HYPERLIQUID_API:
    process.env.HYPERLIQUID_API || "https://api.hyperliquid-testnet.xyz",
  HYPERLIQUID_FXRP_OFT:
    process.env.HYPERLIQUID_FXRP_OFT ||
    "0x14bfb521e318fc3d5e92A8462C65079BC7d4284c",
  // System address for FXRP on testnet (token index 1443 = 0x5A3)
  FXRP_SYSTEM_ADDRESS: "0x20000000000000000000000000000000000005a3",
  FXRP_TOKEN_ID: "FXRP:0x2af78df5b575b45eea8a6a1175026dd6",
  COSTON2_COMPOSER:
    process.env.COSTON2_COMPOSER ||
    "0x5051E8db650E9e0E2a3f03010Ee5c60e79CF583E",
  COSTON2_EID: EndpointId.FLARE_V2_TESTNET,
  EXECUTOR_GAS: 1_000_000, // Gas for receiving on Coston2
  COMPOSE_GAS: 1_000_000, // Gas for compose execution
  SEND_LOTS: "1", // Number of lots to redeem
  XRP_ADDRESS: process.env.XRP_ADDRESS || "rpHuw4bKSjonKRrKKVYYVedg1jyPrmp",
  HYPERLIQUID_CHAIN: "Testnet",
};
```

### How to Run

**PREREQUISITE: You must have FXRP tokens in your HyperCore spot wallet before running this script.**

1. **Deploy FAssetRedeemComposer** (first time only):

   ```bash
   npx hardhat deploy --network coston2 --tags FAssetRedeemComposer
   ```

2. **Configure Environment**:

   ```bash
   # .env file
   HYPERLIQUID_TESTNET_RPC_URL=https://api.hyperliquid-testnet.xyz/evm
   DEPLOYER_PRIVATE_KEY=your_private_key_here
   COSTON2_COMPOSER=0x... # Required! Set this after deploying the composer
   HYPERLIQUID_FXRP_OFT=0x14bfb521e318fc3d5e92A8462C65079BC7d4284c
   XRP_ADDRESS=rYourXRPAddressHere # Your XRP ledger address
   ```

3. **Ensure you have FXRP on HyperCore**:
   - Bridge FXRP to HyperCore using `bridgeToHyperEVM.ts` followed by a transfer to HyperCore.
   - Or acquire FXRP on Hyperliquid's spot market.

4. **Run the Script on Hyperliquid Testnet**:

   ```bash
   yarn hardhat run scripts/fassets/autoRedeemFromHyperCore.ts --network hyperliquidTestnet
   ```

### Expected Output

```
============================================================
FXRP Auto-Redemption from HyperCore
HyperCore → HyperEVM → Coston2 → XRP Ledger
============================================================
Using account: 0x742d35Cc6634C0532925a3b844Bc454e4438f44e
✓ Coston2 Composer configured: 0x5051E8db650E9e0E2a3f03010Ee5c60e79CF583E

📊 Checking HyperCore spot balance...
   HyperCore FXRP balance: 25.0

📤 Step 1: Transferring FXRP from HyperCore to HyperEVM...
   Amount: 10 FXRP
   Destination (system address): 0x20000000000000000000000000000000000005a3
✅ HyperCore → HyperEVM transfer initiated
   Response: {"status":"ok","response":{"type":"default"}}
   Waiting for transfer to settle on HyperEVM...

Connecting to FXRP OFT on HyperEVM: 0x14bfb521e318fc3d5e92A8462C65079BC7d4284c
✓ Connected to FXRP OFT
Token decimals: 6

📋 Redemption Parameters:
Amount: 10.0 FXRP
XRP Address: rpHuw4bKSjonKRrKKVYYVedg1jyPrmp
Redeemer: 0x742d35Cc6634C0532925a3b844Bc454e4438f44e

💰 HyperEVM FXRP balance: 10.0
✓ Sufficient balance on HyperEVM

Compose message encoded for auto-redemption

💵 LayerZero Fee: 0.003456 HYPE

📤 Step 2: Sending FXRP from HyperEVM to Coston2 with auto-redeem...
   Amount: 10.0 FXRP
   Target composer: 0x5051E8db650E9e0E2a3f03010Ee5c60e79CF583E
   XRP destination: rpHuw4bKSjonKRrKKVYYVedg1jyPrmp

✓ Transaction sent: 0xabc123...
✅ Confirmed in block: 9876543

🎉 Success! Auto-redemption initiated!

📊 Track your cross-chain transaction:
https://testnet.layerzeroscan.com/tx/0xabc123...

⏳ The auto-redeem will execute once the message arrives on Coston2.
XRP will be sent to: rpHuw4bKSjonKRrKKVYYVedg1jyPrmp
```

<details>
<summary>View `autoRedeemFromHyperCore.ts` source code</summary>

<CodeBlock
  language="typescript"
  title="scripts/fassets/autoRedeemFromHyperCore.ts"
>
  {autoRedeemFromHyperCore}
</CodeBlock>

</details>

### Troubleshooting

**Error: Insufficient FXRP on HyperCore**

- Solution: Bridge FXRP to HyperCore first or acquire FXRP on Hyperliquid's spot market.

**Error: HyperCore transfer failed**

- Check that your wallet is properly configured with Hyperliquid.
- Verify the EIP-712 signature is being generated correctly.
- Ensure the FXRP_TOKEN_ID matches the correct token on the network.

**Error: Insufficient FXRP balance on HyperEVM**

- The transfer from HyperCore may still be pending.
- Wait a few more seconds and try again.
- Check your HyperEVM balance directly.

**Error: Insufficient HYPE for gas**

- Get HYPE tokens from Hyperliquid testnet [faucet](https://hyperliquid.gitbook.io/hyperliquid-docs/onboarding/testnet-faucet).

## FAQ

**Q: How long does bridging take?**
A: Typically 2-5 minutes for LayerZero message delivery + execution time.

**Q: What's the minimum amount I can bridge?**
A: Any amount for bridging to Hyperliquid. For auto-redeem, minimum is 1 [lot](https://dev.flare.network/fassets/minting#lots) (10 FXRP for XRP).

**Q: Can I bridge to a different address?**
A: Yes, edit the `recipientAddress` parameter in the scripts.

**Q: What happens if compose execution fails?**
A: Tokens will be stuck in the composer. Owner can recover using `recoverTokens()`.

**Q: Can I use this on mainnet?**
A: This is designed for testnet. For mainnet, update contract addresses, thoroughly test, and audit all code.

**Q: How do I get FTestXRP on Flare Testnet Coston2?**
A: Use Flare's FAsset minting process via the AssetManager contract.

**Q: What if I don't have HYPE tokens?**
A: Get them from Hyperliquid testnet [faucet](https://hyperliquid.gitbook.io/hyperliquid-docs/onboarding/testnet-faucet) or DEX.

**Q: What's the difference between HyperCore and HyperEVM?**
A: HyperCore is Hyperliquid's high-performance spot trading layer where tokens are held in spot wallets. HyperEVM is Hyperliquid's EVM-compatible execution environment where tokens exist as ERC-20s. You need to transfer tokens from HyperCore to HyperEVM before bridging via LayerZero.

**Q: Why does the HyperCore transfer use Arbitrum's chainId?**
A: Hyperliquid's API requires Arbitrum's chainId (42161) for all EIP-712 signatures. This is a legacy requirement from when Hyperliquid settled on Arbitrum.

## Discovering Available Bridge Routes

The `getOftPeers.ts` utility script discovers all configured LayerZero peers for the FXRP OFT Adapter on Flare Testnet Coston2.
It scans all LayerZero V2 testnet endpoints to find which EVM chains have been configured as valid bridge destinations.

Before bridging FXRP to another chain, you need to know which chains are supported.
This script:

- Automatically discovers all configured peer addresses
- Shows which EVM chains you can bridge FXRP to/from
- Provides the peer contract addresses for each chain
- Outputs results in both human-readable and JSON formats

#### How It Works

1. **Loads V2 Testnet Endpoints**: Dynamically retrieves all LayerZero V2 testnet endpoint IDs from the [`@layerzerolabs/lz-definitions`](https://docs.layerzero.network/plugins#layerzerolabslz-definitions) package.
2. **Queries Peers**: For each endpoint, calls the `peers()` [function](https://coston2-explorer.flare.network/address/0xCd3d2127935Ae82Af54Fc31cCD9D3440dbF46639?tab=read_write_proxy&source_address=0x82BC5e114D0843160be1cEaB8196Ba91f87473FE#0xbb0b6a53) on the OFT Adapter contract.
3. **Filters Results**: Only shows endpoints that have a non-zero peer address configured.
4. **Formats Output**: Displays results in a table format and as JSON for programmatic use.

#### How to Run

```bash
yarn hardhat run scripts/layerzero/getOFTPeers.ts --network coston2
```

#### Expected Output

```
=== FXRP OFT Adapter Peers Discovery ===

OFT Adapter: 0xCd3d2127935Ae82Af54Fc31cCD9D3440dbF46639
Network: Coston2 (Flare Testnet)

Scanning 221 LayerZero V2 Testnet endpoints...

✅ Bsc (EID: 40102): 0xac7c4a07670589cf83b134a843bfe86c45a4bf4e
✅ Sepolia (EID: 40161): 0x81672c5d42f3573ad95a0bdfbe824faac547d4e6
✅ Hyperliquid (EID: 40362): 0x14bfb521e318fc3d5e92a8462c65079bc7d4284c

============================================================
SUMMARY: Configured Peers
============================================================

Found 3 configured peer(s):

| Chain | EID | Peer Address |
|-------|-----|--------------|
| Bsc | 40102 | 0xac7c4a07670589cf83b134a843bfe86c45a4bf4e |
| Sepolia | 40161 | 0x81672c5d42f3573ad95a0bdfbe824faac547d4e6 |
| Hyperliquid | 40362 | 0x14bfb521e318fc3d5e92a8462c65079bc7d4284c |

--- Available Routes ---
You can bridge FXRP to/from the following chains:

  • Bsc
  • Sepolia
  • Hyperliquid
```

Once you've identified available peers, you can:

1. **Bridge to any discovered chain**: Update the destination EID in `bridgeToHyperEVM.ts` to target a different chain
2. **Verify peer addresses**: Use the peer addresses to interact with OFT contracts on other chains
3. **Build integrations**: Use the JSON output to programmatically determine available routes

<details>
<summary>View `getOftPeers.ts` source code</summary>

<CodeBlock language="typescript" title="scripts/layerzero/getOFTPeers.ts">
  {getOftPeers}
</CodeBlock>

</details>

:::tip Next Steps
To continue your FAssets development journey, you can:

- Learn how to [mint FXRP](/fassets/developer-guides/fassets-mint)
- Understand how to [redeem FXRP](/fassets/developer-guides/fassets-redeem)
- Explore [FAssets system settings](/fassets/operational-parameters)
  :::
