Operation - Swap Out
Key Steps:
Example Code
import { parseUnits } from 'viem';
import { walletClient, publicClient, protocolConfig, collateral, DEBT_TOKEN_DECIMALS } from 'satoshi-sdk';
// Example usage:
doSwapIn('USDT', 1)
.then((receipt) => console.log('Swap-out completed:', receipt))
.catch((error) => console.error('Error during swap-out:', error));
async function doSwapOut(assetSymbol: string, amount: number) {
// Initialize the SatoshiClient with protocol and wallet configurations
const satoshiClient = new SatoshiClient(protocolConfig, walletClient);
const asset = (satoshiClient.NexusYieldModule.getAssetList()).find(t => t.symbol === assetSymbol)!;
// Fetch the current SAT balance before the swap
const satBalanceBefore = await getBalanceOf(debtAddress);
// Define the amount of SAT to swap out, converting to the appropriate units
const satAmount = parseUnits(amount.toString(), DEBT_TOKEN_DECIMALS);
// Preview the swap-out to get information on the expected asset amount and fees
const previewSwapOut = await satoshiClient.NexusYieldModule.getPreviewSwapOut(asset.address, satAmount);
const expectedReceiveAssetAmt = Number(previewSwapOut?.assetAmount); // Asset amount expected to be received
// Execute the swap-out operation
const receipt = await satoshiClient.NexusYieldModule.doNymSwapOut(asset.address, satAmount);
// Fetch the SAT balance after the swap to validate the amount swapped out
const satBalanceAfter = await getBalanceOf(debtAddress);
// Confirm that the swap was successful
if (receipt.status !== 'success') {
throw new Error('Swap-out transaction failed.');
}
// Validate that the SAT balance decreased by the amount swapped out
const swappedAmount = satBalanceBefore - satBalanceAfter;
if (swappedAmount !== satAmount) {
throw new Error(`Balance mismatch: expected to swap out ${satAmount}, but got ${swappedAmount}`);
}
console.log('Swap-out was successful:', receipt);
return receipt;
}
Last updated