Staking & Farming Tutorial

Learn how to stake tokens and earn rewards using the Saros SDK with this comprehensive guide.

Overview

This tutorial will guide you through the process of staking LP tokens in farms and claiming rewards using the Saros SDK. Staking allows you to earn additional tokens as rewards for supporting the protocol.

40 min
Estimated Time
Intermediate
Difficulty
Solana
Blockchain

1. Prerequisites

Before starting this tutorial, ensure you have the following:

  • Node.js 16+ and npm/yarn installed
  • Basic knowledge of TypeScript/JavaScript
  • A Solana wallet with some SOL for transaction fees
  • LP tokens to stake (obtained by providing liquidity to pools)
  • Understanding of staking and farming concepts (recommended)
Install Dependencies
// Install the required packages
npm install @saros-finance/sdk @solana/web3.js

// Import the necessary modules
import sarosSdk, { genConnectionSolana } from '@saros-finance/sdk';
import { PublicKey } from '@solana/web3.js';
import BN from 'bn.js';

// Extract the services we need
const { SarosFarmService, SarosStakeServices } = sarosSdk;

2. Set up Connection

First, we need to establish a connection to the Solana network and configure our wallet.

Connection Setup
// Generate a connection to the Solana network
const connection = genConnectionSolana();

// Define your wallet address (in a real app, this would come from a connected wallet)
const accountSol = 'YOUR_WALLET_PUBLIC_KEY';

// Define the payer account object
const payerAccount = { publicKey: new PublicKey(accountSol) };

3. Configure Farm

Set up the farm parameters for staking operations. You'll need to know the farm address and reward information.

Farm Configuration
// Configure the farm parameters
const SAROS_FARM_ADDRESS = new PublicKey('SFarmWM5wLFNEw1q5ofqL7CrwBMwdcqQgK6oQuoBGZJ');

const farmParam = {
  lpAddress: 'HVUeNVH93PAFwJ67ENJwPWFU9cWcM57HEAmkFLFTcZkj',
  poolAddress: 'FW9hgAiUsFYpqjHaGCGw4nAvejz4tAp9qU7kFpYr1fQZ',
  poolLpAddress: '2wUvdZA8ZsY714Y5wUL9fkFmupJGGwzui2N74zqJWgty',
  rewards: [
    {
      address: 'C98A4nkJXhpVZNAZdHUA95RpTF3T4whtQubL3YobiUX9',
      poolRewardAddress: 'AC3FyChJwuU7EY9h4BqzjcN8CtGD7YRrAbeRdjcqe1AW',
      rewardPerBlock: 6600000,
      rewardTokenAccount: 'F6aHSR3ChwCXD67wrX2ZBHMkmmU9Gfm9QQmiTBrKvsmJ',
      id: 'coin98'
    },
  ],
  token0: 'C98A4nkJXhpVZNAZdHUA95RpTF3T4whtQubL3YobiUX9',
  token1: 'EPjFWdd5AufqSSqeM2qN1zzybapC8G4wEGGkZwyTDt1v',
  token0Id: 'coin98',
  token1Id: 'usd-coin'
};

4. List Available Farms

Retrieve a list of available farms to see what staking opportunities are available.

List Farms
// Get a list of available farms
try {
  const response = await SarosFarmService.getListPool({page: 1, size: 10});
  console.log('Available Farms:', response);
  return response;
} catch(err) {
  console.error('Error fetching farms:', err);
  return [];
}

5. Stake Tokens

Stake your LP tokens in a farm to begin earning rewards.

Stake Tokens
// Stake LP tokens in a farm
const stakeAmount = new BN(100 * 1e6); // 100 tokens (6 decimals)

const hash = await SarosFarmService.stakePool(
  connection,
  payerAccount,
  new PublicKey(farmParam.poolAddress),
  stakeAmount,
  SAROS_FARM_ADDRESS,
  farmParam.rewards,
  new PublicKey(farmParam.lpAddress)
);

console.log(`Staking successful! Transaction hash: ${hash}`);
Understanding Staking
1. Prepare Amount: We specify the amount of LP tokens to stake using BN (BigNumber) for precision.
2. Execute Staking: We use SarosFarmService.stakePool to stake tokens in the farm.
3. Receive Confirmation: The function returns a transaction hash to confirm the staking operation.

6. Unstake Tokens

Unstake your LP tokens from a farm when you want to stop earning rewards.

Unstake Tokens
// Unstake LP tokens from a farm
const unStakeAmount = new BN(50 * 1e6); // 50 tokens (6 decimals)

const hash = await SarosFarmService.unStakePool(
  connection,
  payerAccount,
  new PublicKey(farmParam.poolAddress),
  new PublicKey(farmParam.lpAddress),
  unStakeAmount,
  SAROS_FARM_ADDRESS,
  farmParam.rewards,
  false // Set to true if want to unstake full balance
);

console.log(`Unstaking successful! Transaction hash: ${hash}`);
Understanding Unstaking
1. Prepare Amount: We specify the amount of LP tokens to unstake.
2. Execute Unstaking: We use SarosFarmService.unStakePool to unstake tokens from the farm.
3. Receive Tokens: The LP tokens are returned to your wallet.

7. Claim Rewards

Claim the rewards you've earned from staking your LP tokens.

Claim Rewards
// Claim rewards from a farm
const poolRewardAddress = farmParam.rewards[0].poolRewardAddress;
const mintAddress = farmParam.rewards[0].address;

const hash = await SarosFarmService.claimReward(
  connection,
  payerAccount,
  new PublicKey(poolRewardAddress),
  new PublicKey(SAROS_FARM_ADDRESS),
  new PublicKey(mintAddress)
);

console.log(`Rewards claimed! Transaction hash: ${hash}`);
Understanding Rewards
1. Calculate Rewards: The protocol calculates the rewards you've earned based on your stake and time.
2. Execute Claim: We use SarosFarmService.claimReward to claim your rewards.
3. Receive Tokens: The reward tokens are sent to your wallet.
📚 Next Steps
Continue learning with these related tutorials
💡 Key Takeaways
Lock-up Periods: Some farms may have lock-up periods during which you cannot unstake your tokens.
Reward Calculation: Rewards are typically calculated based on your share of the pool and the time you've been staking.
Compound Rewards: Consider reinvesting your rewards to maximize your earnings over time.
Risk Management: Understand the risks associated with staking, including smart contract risks and impermanent loss.
Network Configuration: Use the correct RPC endpoints for devnet, testnet, or mainnet depending on your environment.