Yield Farming Tutorial

Learn how to participate in yield farming programs using the Saros SDK with this comprehensive guide.

Overview

This tutorial will guide you through the process of participating in yield farming programs using the Saros SDK. Yield farming allows you to earn additional tokens as rewards for staking your LP tokens in farming pools.

35 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 farm (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 } = 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 farming 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 farming 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. Start Farming

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

Start Farming
// Stake LP tokens in a farm to begin farming
const farmAmount = new BN(100 * 1e6); // 100 tokens (6 decimals)

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

console.log(`Farming started! Transaction hash: ${hash}`);
Understanding Farming
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 farming 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(`Tokens unstaked! 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 farming 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.
Key Farming Concepts

APY (Annual Percentage Yield)

The annual rate of return you can expect from farming, taking into account compounding.

Reward Tokens

Additional tokens distributed to farmers as incentives for providing liquidity.

Lock-up Periods

Some farms may have lock-up periods during which you cannot unstake your tokens.

Impermanent Loss

The potential loss of value when providing liquidity compared to holding tokens, which also affects farming.

📚 Next Steps
Continue learning with these related tutorials
💡 Key Takeaways
Risk vs Reward: Higher APY farms may come with higher risks, including impermanent loss and smart contract risks.
Diversification: Consider diversifying your farming across multiple pools to reduce risk.
Compound Rewards: Reinvesting your rewards can significantly increase your returns over time.
Monitor Performance: Regularly check the performance of your farming positions and adjust as needed.
Network Configuration: Use the correct RPC endpoints for devnet, testnet, or mainnet depending on your environment.