# Claim LP Rewards

In this section, we demonstrate how to claim accrued rewards from a specific Aquarius AMM pool. For this example, we will use this [this XLM-AQUA pool](https://aqua.network/pools/CCY2PXGMKNQHO7WNYXEWX76L2C5BH3JUW3RCATGUYKY7QQTRILBZIFWV/).

To claim your rewards, you need to make a deposit in the pool where the rewards are distributed. Rewards are accrued every second.&#x20;

Scroll [here](#complete-code-examples) to see the complete code.

### Executing Claim: Step by Step Guide

1. **Specify user secret key and pool address:** To claim from a pool, you need your **user secret key** and the **pool address** from which you want to claim the rewards.

{% tabs %}
{% tab title="Python" %}

```python
# Distributor's secret key (ensure this is kept secure)
user_secret_key = "S..."
# XLM/AQUA pool address 
pool_address = "CCY2PXGMKNQHO7WNYXEWX76L2C5BH3JUW3RCATGUYKY7QQTRILBZIFWV"
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
// Distributor's secret key (ensure this is kept secure)
const userSecretKey = "S...";
// XLM/AQUA pool address 
const poolAddress = "CCY2PXGMKNQHO7WNYXEWX76L2C5BH3JUW3RCATGUYKY7QQTRILBZIFWV";
```

{% endtab %}
{% endtabs %}

2. **Make a contract call to the pool's "claim" method.**

{% tabs %}
{% tab title="Python" %}

```python
def execute_claim():
   # Initialize Soroban and Horizon servers
   server = SorobanServer(SOROBAN_SERVER_RPC)
   horizon_server = Server(HORIZON_SERVER)

   # Load distributor's keypair using the secret key
   keypair = Keypair.from_secret(user_secret_key)

   # Load the distributor's account information from Soroban server
   account = server.load_account(keypair.public_key)

   # Build the claim transaction
   tx_builder = TransactionBuilder(
       source_account=account,
       network_passphrase=NETWORK_PASSPHRASE,
       base_fee=1000000  # Set base fee; adjust as necessary
   ).set_timeout(3600)  # Set transaction timeout

   # Append the invoke_contract_function operation for claim
   tx = tx_builder.append_invoke_contract_function_op(
       contract_id=pool_address,
       function_name="claim",
       parameters=[
           Address(keypair.public_key).to_xdr_sc_val(),  # Distributor's address
       ],
   )
   tx = server.prepare_transaction(tx.build())
   tx.sign(keypair)

   tx_response = horizon_server.submit_transaction(tx)
   transaction_meta = xdr.TransactionMeta.from_xdr(tx_response['result_meta_xdr'])
   tx_result = transaction_meta.v3.soroban_meta.return_value
   if not tx_result:
       raise RuntimeError

   amount = u128_to_int(tx_result.u128)
   print("Claim successful!")
   print(f"Received {amount / 10 ** 7} AQUA")
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
async function executeClaim() {
    const sorobanServer = new rpc.Server(sorobanServerUrl);
    const horizonServer = new Horizon.Server(horizonServerUrl);

    // Load distributor's keypair using the secret key
    const keypair = Keypair.fromSecret(userSecretKey);
    
    // Load the distributor's account information from Soroban server
    const account = await sorobanServer.getAccount(keypair.publicKey());

    const contract = new Contract(poolAddress);

    // Build the claim transaction
    const tx = new TransactionBuilder(account, {
        fee: BASE_FEE,
        networkPassphrase: Networks.PUBLIC,
    })
    // Append the invoke_contract_function operation for claim
    .addOperation(contract.call(
        'claim',
        xdr.ScVal.scvAddress(Address.fromString(keypair.publicKey()).toScAddress()), // Distributor's address
    )).setTimeout(TimeoutInfinite).build();

    const preparedTx = await sorobanServer.prepareTransaction(tx);

    preparedTx.sign(keypair);

    const result = await horizonServer.submitTransaction(preparedTx);

    const meta = (await sorobanServer.getTransaction(result.id)).resultMetaXdr;

    const returnValue = meta.v3().sorobanMeta().returnValue();

    const amount = u128ToInt(returnValue.value());

    console.log('Claim successful!');
    console.log(`Received: ${amount / 1e7} AQUA`);
}
```

{% endtab %}
{% endtabs %}

## Complete Code Examples

This code claim rewards from the pool with Aquarius AMM on mainnet.

To successfully execute the code, provide the secret key of a Stellar account with share in the pool where the rewards are distributed.

<details>

<summary>Copy the full code Python</summary>

```python
# claim.py

from typing import List

from stellar_sdk import Address, Keypair, scval, SorobanServer, xdr, TransactionBuilder, Server, Network
from stellar_sdk.xdr import UInt128Parts

# Step 1. Specify user secret key, amount for claim and pool address
# Distributor's secret key (ensure this is kept secure)
user_secret_key = "S..."
# XLM/AQUA pool address 
pool_address = "CCY2PXGMKNQHO7WNYXEWX76L2C5BH3JUW3RCATGUYKY7QQTRILBZIFWV"

# ==========================
# Configuration Variables
# ==========================

# Soroban and Horizon server RPC endpoints
SOROBAN_SERVER_RPC = 'https://mainnet.sorobanrpc.com'
HORIZON_SERVER = 'https://horizon.stellar.org'

# Stellar network passphrase
NETWORK_PASSPHRASE = Network.PUBLIC_NETWORK_PASSPHRASE

# ==========================
# Utility Functions
# ==========================

def u128_to_int(value: UInt128Parts) -> int:
   """
   Converts UInt128Parts from Stellar's XDR to a Python integer.

   Args:
       value (UInt128Parts): UInt128Parts object from Stellar SDK.

   Returns:
       int: Corresponding Python integer.
   """
   return int(value.hi.uint64 << 64) + value.lo.uint64


# ==========================
# Claim Function
# ==========================

# Step 2. Make a contract call to the pool's "claim" method.
def execute_claim():
   # Initialize Soroban and Horizon servers
   server = SorobanServer(SOROBAN_SERVER_RPC)
   horizon_server = Server(HORIZON_SERVER)

   # Load distributor's keypair using the secret key
   keypair = Keypair.from_secret(user_secret_key)

   # Load the distributor's account information from Soroban server
   account = server.load_account(keypair.public_key)

   # Build the claim transaction
   tx_builder = TransactionBuilder(
       source_account=account,
       network_passphrase=NETWORK_PASSPHRASE,
       base_fee=1000000  # Set base fee; adjust as necessary
   ).set_timeout(3600)  # Set transaction timeout

   # Append the invoke_contract_function operation for claim
   tx = tx_builder.append_invoke_contract_function_op(
       contract_id=pool_address,
       function_name="claim",
       parameters=[
           Address(keypair.public_key).to_xdr_sc_val(),  # Distributor's address
       ],
   )
   tx = server.prepare_transaction(tx.build())
   tx.sign(keypair)

   tx_response = horizon_server.submit_transaction(tx)
   transaction_meta = xdr.TransactionMeta.from_xdr(tx_response['result_meta_xdr'])
   tx_result = transaction_meta.v3.soroban_meta.return_value
   if not tx_result:
       raise RuntimeError

   amount = u128_to_int(tx_result.u128)
   print("Claim successful!")
   print(f"Received {amount / 10 ** 7} AQUA")


# ==========================
# Entry Point
# ==========================
if __name__ == "__main__":
   execute_claim()
```

</details>

<details>

<summary>Copy the full code JavaScript</summary>

```javascript
const StellarSdk = require('@stellar/stellar-sdk');
const {
    Address,
    Contract,
    TransactionBuilder,
    rpc,
    Horizon,
    BASE_FEE,
    Networks,
    xdr,
    TimeoutInfinite,
    Keypair,
} = StellarSdk;

// Step 1. Specify user secret key, amount for claim and pool addresss
// Distributor's secret key (ensure this is kept secure)
const userSecretKey = "S...";
// XLM/AQUA pool address 
const poolAddress = "CCY2PXGMKNQHO7WNYXEWX76L2C5BH3JUW3RCATGUYKY7QQTRILBZIFWV";

// ==========================
// Configuration Variables
// ==========================

// Soroban and Horizon server RPC endpoints
const sorobanServerUrl = 'https://mainnet.sorobanrpc.com';
const horizonServerUrl = 'https://horizon.stellar.org';

// ==========================
// Utility Functions
// ==========================

function u128ToInt(value) {
    /**
     * Converts UInt128Parts from Stellar's XDR to a JavaScript number.
     *
     * @param {Object} value - UInt128Parts object from Stellar SDK, with `hi` and `lo` properties.
     * @returns {number|null} Corresponding JavaScript number, or null if the number is too large.
     */
    const result = (BigInt(value.hi()._value) << 64n) + BigInt(value.lo()._value);

    // Check if the result is within the safe integer range for JavaScript numbers
    if (result <= BigInt(Number.MAX_SAFE_INTEGER)) {
        return Number(result);
    } else {
        console.warn("Value exceeds JavaScript's safe integer range");
        return null;
    }
}

// ==========================
// Claim Function
// ==========================

// Step 2. Make a contract call to the pool's "claim" method.
async function executeClaim() {
    const sorobanServer = new rpc.Server(sorobanServerUrl);
    const horizonServer = new Horizon.Server(horizonServerUrl);

    // Load distributor's keypair using the secret key
    const keypair = Keypair.fromSecret(userSecretKey);
    
    // Load the distributor's account information from Soroban server
    const account = await sorobanServer.getAccount(keypair.publicKey());

    const contract = new Contract(poolAddress);

    // Build the claim transaction
    const tx = new TransactionBuilder(account, {
        fee: BASE_FEE,
        networkPassphrase: Networks.PUBLIC,
    })
    // Append the invoke_contract_function operation for claim
    .addOperation(contract.call(
        'claim',
        xdr.ScVal.scvAddress(Address.fromString(keypair.publicKey()).toScAddress()), // Distributor's address
    )).setTimeout(TimeoutInfinite).build();

    const preparedTx = await sorobanServer.prepareTransaction(tx);

    preparedTx.sign(keypair);

    const result = await horizonServer.submitTransaction(preparedTx);

    const meta = (await sorobanServer.getTransaction(result.id)).resultMetaXdr;

    const returnValue = meta.v3().sorobanMeta().returnValue();

    const amount = u128ToInt(returnValue.value());

    console.log('Claim successful!');
    console.log(`Received: ${amount / 1e7} AQUA`);
}

// ==========================
// Entry Point
// ==========================
executeClaim();
```

</details>


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.aqua.network/developers/code-examples/claim-lp-rewards.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
