Learn how to swap tokens using the Saros SDK with this complete example.
import { getSwapAmountSaros, swapSaros, genConnectionSolana } from '@saros-finance/sdk';
import { PublicKey } from '@solana/web3.js';
const connection = genConnectionSolana();
const accountSol = 'YOUR_WALLET_PUBLIC_KEY';
const USDC_TOKEN = {
mintAddress: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',
addressSPL: 'FXRiEosEvHnpc3XZY1NS7an2PB1SunnYW1f5zppYhXb3',
decimals: '6'
};
const C98_TOKEN = {
mintAddress: 'C98A4nkJXhpVZNAZdHUA95RpTF3T4whtQubL3YobiUX9',
addressSPL: 'EKCdCBjfQ6t5FBfDC2zvmr27PgfVVZU37C8LUE4UenKb',
decimals: '6'
};
const poolParams = {
address: '2wUvdZA8ZsY714Y5wUL9fkFmupJGGwzui2N74zqJWgty',
tokens: {
C98A4nkJXhpVZNAZdHUA95RpTF3T4whtQubL3YobiUX9: C98_TOKEN,
EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v: USDC_TOKEN,
},
tokenIds: [
'C98A4nkJXhpVZNAZdHUA95RpTF3T4whtQubL3YobiUX9',
'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',
],
};
async function performSwap() {
try {
// Get swap quote
const estSwap = await getSwapAmountSaros(
connection,
C98_TOKEN.mintAddress,
USDC_TOKEN.mintAddress,
1, // 1 C98
0.5, // 0.5% slippage
poolParams
);
console.log('Estimated swap:', estSwap);
// Execute swap
const result = await swapSaros(
connection,
C98_TOKEN.addressSPL,
USDC_TOKEN.addressSPL,
1,
estSwap.amountOutWithSlippage,
null,
new PublicKey(poolParams.address),
new PublicKey('SSwapUtytfBdBn1b9NUGG6foMVPtcWgpRU32HToDUZr'), // Program address
accountSol,
C98_TOKEN.mintAddress,
USDC_TOKEN.mintAddress
);
if (result.isError) {
console.error('Swap failed:', result.mess);
return { success: false, message: result.mess };
} else {
console.log('Swap successful! Hash:', result.hash);
return { success: true, hash: result.hash };
}
} catch (error) {
console.error('Error:', error);
return { success: false, message: error.message };
}
}
// Execute the swap
performSwap().then(result => {
if (result.success) {
console.log("Transaction completed with hash:", result.hash);
} else {
console.log("Transaction failed:", result.message);
}
});
This simulation demonstrates the expected behavior of the swap function. In a real application, this would connect to the Solana network.
Click 'Run Swap Simulation' to see the output here...
genConnectionSolana()
initializes a connection to the Solana network.
Define token objects with mint addresses and SPL token accounts.
Specify the pool address and token information for the swap.
getSwapAmountSaros
calculates the output amount, and swapSaros
executes the transaction.