Get up and running with the Saros Finance SDK in minutes. This guide covers installation, basic setup, and your first swap operation.
Install the Saros Finance SDK using your preferred package manager:
npm install @saros-finance/sdk
# or
yarn add @saros-finance/sdk
Import the necessary functions and set up your connection:
import sarosSdk, {
getSwapAmountSaros,
swapSaros,
createPool,
getPoolInfo,
depositAllTokenTypes,
withdrawAllTokenTypes,
convertBalanceToWei,
genConnectionSolana,
} from '@saros-finance/sdk';
import { PublicKey } from '@solana/web3.js';
import BN from 'bn.js';
const { SarosFarmService, SarosStakeServices } = sarosSdk;
const connection = genConnectionSolana();
const accountSol = 'YOUR_WALLET_PUBLIC_KEY';
let payerAccount = { publicKey: undefined };
try {
payerAccount.publicKey = new PublicKey(accountSol);
} catch (e) {
// ignore
}
Define your token configurations for the swap:
const USDC_TOKEN = {
id: 'usd-coin',
mintAddress: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',
symbol: 'usdc',
name: 'USD Coin',
decimals: '6',
addressSPL: 'FXRiEosEvHnpc3XZY1NS7an2PB1SunnYW1f5zppYhXb3',
};
const C98_TOKEN = {
id: 'coin98',
mintAddress: 'C98A4nkJXhpVZNAZdHUA95RpTF3T4whtQubL3YobiUX9',
symbol: 'C98',
name: 'Coin98',
decimals: '6',
addressSPL: 'EKCdCBjfQ6t5FBfDC2zvmr27PgfVVZU37C8LUE4UenKb',
};
To interact with a specific pool, you need its address and the mint addresses of the tokens it contains. You can find this information using a block explorer like Solscan or by using the SDK to fetch a list of available pools.
The SarosFarmService
and SarosStakeServices
can be used to fetch lists of available pools, which include the necessary addresses.
Now let's perform a token swap using the SDK:
const onSwap = async () => {
const fromTokenAccount = C98_TOKEN.addressSPL;
const toTokenAccount = USDC_TOKEN.addressSPL;
const fromMint = C98_TOKEN.mintAddress;
const toMint = USDC_TOKEN.mintAddress;
const fromAmount = 1;
const SLIPPAGE = 0.5;
// Get swap quote
const estSwap = await getSwapAmountSaros(
connection,
fromMint,
toMint,
fromAmount,
SLIPPAGE,
poolParams
);
const { amountOutWithSlippage } = estSwap;
// Execute swap
const result = await swapSaros(
connection,
fromTokenAccount.toString(),
toTokenAccount.toString(),
parseFloat(fromAmount.toString()),
parseFloat(amountOutWithSlippage),
null,
new PublicKey(poolParams.address),
SAROS_SWAP_PROGRAM_ADDRESS_V1,
accountSol,
fromMint,
toMint
);
if (result.isError) {
return console.log(result.mess);
}
return "Your transaction hash " + result.hash;
};
getSwapAmountSaros
to calculate the expected output amount and apply slippage protection.swapSaros
to perform the actual token exchange on-chain.