# Example

This guide provides a simple example of how to claim rewards on something.cool using js.

## Prerequisites

Install the required packages:

```bash
npm install @solana/web3.js bs58 tweetnacl axios
```

## Simple JavaScript Example

```javascript
const { Connection, PublicKey, Transaction, Keypair } = require("@solana/web3.js")
const bs58 = require("bs58")
const nacl = require("tweetnacl")
const axios = require("axios")

// Configuration
const API_URL = "TBA/api/v1"
const RPC_URL = "https://api.mainnet-beta.solana.com"

// Your wallet's private key (in production, use secure key management)
const privateKey = "YOUR_PRIVATE_KEY_HERE" // Replace with your private key
const wallet = Keypair.fromSecretKey(bs58.decode(privateKey))
const walletAddress = wallet.publicKey.toString()

// Token you want to claim rewards for
const tokenAddress = "TokenAddressHere" // Replace with token address
const claimType = "SOL" // or 'TOKEN'

// Create Solana connection
const connection = new Connection(RPC_URL)

// Function to claim rewards
async function claimRewards() {
  // Step 1: Generate and sign timestamp
  const timestamp = Date.now().toString()
  const timestampBytes = Buffer.from(timestamp)
  const signature = nacl.sign.detached(timestampBytes, wallet.secretKey)
  const signatureBase58 = bs58.encode(signature)

  // Step 2: Get claimable rewards for the token
  const tokenRewardsResponse = await axios.get(
    `${API_URL}/rewards/${walletAddress}/tokens/${tokenAddress}`,
    {
      headers: {
        "X-Signature": signatureBase58,
        "X-Timestamp": timestamp,
      },
    }
  )

  console.log("Claimable rewards:", tokenRewardsResponse.data)

  // Check if there are rewards to claim
  if (
    tokenRewardsResponse.data.status === "success" &&
    tokenRewardsResponse.data.data.unclaimedRewards[claimType.toLowerCase()] > 0
  ) {
    console.log("Timestamp signed successfully")

    // Step 3: Initiate claim
    const claimResponse = await axios.post(
      `${API_URL}/rewards/${walletAddress}/initiate`,
      {
        tokenAddress,
        claimType,
        burnToken: false,
      },
      {
        headers: {
          "Content-Type": "application/json",
          "X-Signature": signatureBase58,
          "X-Timestamp": timestamp,
        },
      }
    )

    if (claimResponse.data.status === "success") {
      // Step 4: Process and sign the transaction
      const transactionBase64 = claimResponse.data.data.tx
      const transactionBuffer = Buffer.from(transactionBase64, "base64")
      const transaction = Transaction.from(transactionBuffer)

      // Sign the transaction
      transaction.partialSign(wallet)

      // Step 5: Send transaction to the network
      const rawTransaction = transaction.serialize()
      const txSignature = await connection.sendRawTransaction(rawTransaction)

      console.log("Transaction sent:", txSignature)

      // Wait for confirmation
      const confirmation = await connection.confirmTransaction(txSignature)
      console.log("Transaction confirmed:", confirmation)

      // Step 6: Check claim status
      const statusResponse = await axios.get(`${API_URL}/rewards/${txSignature}/status`)

      console.log("Claim status:", statusResponse.data)
      return txSignature
    } else {
      console.error("Failed to initiate claim:", claimResponse.data)
    }
  } else {
    console.log("No rewards available to claim")
  }
}

// Run the claim function
claimRewards()
  .then((signature) => console.log("Claim process complete! Signature:", signature))
  .catch((error) => console.error("Claim process failed:", error))
```

## How It Works

1. **Sign a Timestamp**
   * Generates current timestamp
   * Signs it with your wallet's private key
   * Encodes the signature in base58
2. **Check Available Rewards**
   * Makes a GET request to `/rewards/:address/tokens/:tokenAddress`
   * Checks if there are rewards available to claim
3. **Initiate the Claim**
   * Sends a POST request to `/rewards/:address/initiate`
   * Includes the signature and timestamp in headers
   * Receives a partially signed transaction
4. **Complete the Transaction**
   * Deserializes the transaction
   * Signs it with your wallet
   * Submits it to the Solana network
5. **Verify the Claim**
   * Checks the transaction status using the API

## Important Notes

* Keep your private key secure! The example above is for demonstration only.
* The API URL will be announced when the service is live.
* Signatures expire after 5 minutes.
* Each transaction requires a small amount of SOL for fees.


---

# 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.something.cool/rewards-claiming/example.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.
