Skip to content

Currency Swaps

The Swap Service provides API endpoints for exchanging between different cryptocurrencies. This guide walks you through getting exchange rates, executing swaps, and monitoring transactions.

Overview

The Swap Service enables the seamless exchange of cryptocurrencies with a straightforward API. It’s designed to abstract away the complexities of cross-asset trading, allowing applications to offer currency conversion without building complex swap infrastructure.

Key Features

  • Get real-time exchange rates between supported currency pairs
  • Execute swaps between any supported cryptocurrencies
  • Track swap transactions from initiation to completion
  • Query supported currencies and their details
  • Filter and manage swap history at wallet and organization levels

Prerequisites

Before using the Swap Service:

  1. You need a valid API key with appropriate permissions
  2. Understand the currencies you want to swap between
  3. Have a wallet with sufficient balance of the source currency

Checking Exchange Rates

Before initiating a swap, you should check the current exchange rate between your desired currency pair.

const getExchangeRate = async (sourceCurrency, destinationCurrency) => {
const response = await fetch(
`https://api.fsco.io/v2/swap/rate/${sourceCurrency}/${destinationCurrency}`,
{
headers: {
'Authorization': 'Bearer YOUR_API_KEY'
}
}
);
const data = await response.json();
console.log(`Exchange rate: 1 ${sourceCurrency} = ${data.rate} ${destinationCurrency}`);
return data;
};
// Example usage
getExchangeRate('USDC', 'ETH').then(data => {
console.log(`Current rate: ${data.rate}`);
});

Response Example

{
"rate": "0.00054321",
"sourceCurrency": "USDC",
"destinationCurrency": "ETH"
}

Initiating a Swap

Once you’re satisfied with the exchange rate, you can initiate a swap operation.

const initiateSwap = async (sourceCurrency, destinationCurrency, amount, walletId) => {
const response = await fetch('https://api.fsco.io/v2/swap/initiate', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer YOUR_API_KEY'
},
body: JSON.stringify({
sourceCurrency,
destinationCurrency,
amount,
walletId
})
});
const result = await response.json();
console.log(`Swap initiated with transaction ID: ${result.queryId}`);
return result;
};
// Example usage
initiateSwap('USDC', 'ETH', '1000', 'wallet-uuid-here').then(result => {
console.log(`Track your swap with transaction ID: ${result.queryId}`);
});

Response Example

{
"queryId": "123e4567-e89b-12d3-a456-426614174000"
}

Tracking a Swap Transaction

After initiating a swap, you can check its status using the transaction ID.

const getSwapTransaction = async (transactionId) => {
const response = await fetch(
`https://api.fsco.io/v2/swap/transaction/${transactionId}`,
{
headers: {
'Authorization': 'Bearer YOUR_API_KEY'
}
}
);
const transaction = await response.json();
console.log(`Swap status: ${transaction.status}`);
return transaction;
};
// Example usage
getSwapTransaction('123e4567-e89b-12d3-a456-426614174000').then(transaction => {
console.log(`Swap details:`, transaction);
});

Response Example

{
"id": "123e4567-e89b-12d3-a456-426614174000",
"sourceCurrency": "USDC",
"destinationCurrency": "ETH",
"sourceAmount": "1000.00",
"destinationAmount": "0.54321",
"rate": "0.00054321",
"status": "completed",
"walletId": "wallet-uuid-here",
"organisationId": "org-uuid-here",
"createdAt": "2023-11-05T12:30:45Z",
"completedAt": "2023-11-05T12:31:15Z"
}

Viewing Swap Transaction History

You can retrieve the history of swap transactions for a specific wallet or organization.

const getSwapTransactions = async (walletId = null, organisationId = null, status = null, page = 1, pageSize = 10) => {
let url = `https://api.fsco.io/v2/swap/transactions?page=${page}&pageSize=${pageSize}`;
if (walletId) url += `&walletId=${walletId}`;
if (organisationId) url += `&organisationId=${organisationId}`;
if (status) url += `&status=${status}`;
const response = await fetch(url, {
headers: {
'Authorization': 'Bearer YOUR_API_KEY'
}
});
const result = await response.json();
console.log(`Found ${result.transactions.length} transactions`);
return result;
};
// Example usage
getSwapTransactions('wallet-uuid-here', null, 'completed').then(result => {
console.log(`Total pages: ${result.meta.totalPages}`);
console.log(`Transactions:`, result.transactions);
});

Response Example

{
"transactions": [
{
"id": "123e4567-e89b-12d3-a456-426614174000",
"sourceCurrency": "USDC",
"destinationCurrency": "ETH",
"sourceAmount": "1000.00",
"destinationAmount": "0.54321",
"rate": "0.00054321",
"status": "completed",
"walletId": "wallet-uuid-here",
"organisationId": "org-uuid-here",
"createdAt": "2023-11-05T12:30:45Z",
"completedAt": "2023-11-05T12:31:15Z"
},
{
"id": "223e4567-e89b-12d3-a456-426614174001",
"sourceCurrency": "ETH",
"destinationCurrency": "USDC",
"sourceAmount": "0.5",
"destinationAmount": "920.75",
"rate": "1841.5",
"status": "completed",
"walletId": "wallet-uuid-here",
"organisationId": "org-uuid-here",
"createdAt": "2023-11-04T15:22:10Z",
"completedAt": "2023-11-04T15:22:45Z"
}
],
"meta": {
"page": 1,
"pageSize": 10,
"totalPages": 1,
"totalCount": 2
}
}

Getting Supported Currencies

Before attempting a swap, you can check which currencies are supported by the service.

const getSupportedCurrencies = async () => {
const response = await fetch('https://api.fsco.io/v2/swap/supported-currencies', {
headers: {
'Authorization': 'Bearer YOUR_API_KEY'
}
});
const currencies = await response.json();
console.log(`Found ${currencies.length} supported currencies`);
return currencies;
};
// Example usage
getSupportedCurrencies().then(currencies => {
const stablecoins = currencies.filter(c => c.isStablecoin);
console.log(`Supported stablecoins: ${stablecoins.map(c => c.code).join(', ')}`);
});

Response Example

[
{
"code": "ETH",
"name": "Ethereum",
"decimals": 18,
"isStablecoin": false,
"network": "Ethereum"
},
{
"code": "USDC",
"name": "USD Coin",
"decimals": 6,
"isStablecoin": true,
"network": "Ethereum"
},
{
"code": "USDT",
"name": "Tether",
"decimals": 6,
"isStablecoin": true,
"network": "Ethereum"
},
{
"code": "BTC",
"name": "Bitcoin",
"decimals": 8,
"isStablecoin": false,
"network": "Bitcoin"
}
]

Common Swap Scenarios

Stablecoin to Cryptocurrency

Converting from a stablecoin (like USDC) to a cryptocurrency (like ETH) is one of the most common swap operations.

async function convertStablecoinToCrypto(walletId, stablecoinAmount) {
// 1. Get current exchange rate
const rateInfo = await getExchangeRate('USDC', 'ETH');
console.log(`Current rate: 1 USDC = ${rateInfo.rate} ETH`);
// 2. Confirm the expected output amount
const expectedEthAmount = parseFloat(stablecoinAmount) * parseFloat(rateInfo.rate);
console.log(`Expected ETH: ${expectedEthAmount}`);
// 3. Execute the swap
const swapResult = await initiateSwap('USDC', 'ETH', stablecoinAmount, walletId);
// 4. Track the swap transaction
let swapTransaction;
let checkInterval = setInterval(async () => {
swapTransaction = await getSwapTransaction(swapResult.queryId);
console.log(`Swap status: ${swapTransaction.status}`);
if (swapTransaction.status !== 'pending') {
clearInterval(checkInterval);
if (swapTransaction.status === 'completed') {
console.log(`Swap completed! Received ${swapTransaction.destinationAmount} ETH`);
} else {
console.error(`Swap failed: ${swapTransaction.errorMessage}`);
}
}
}, 5000); // Check every 5 seconds
}
// Example usage
convertStablecoinToCrypto('wallet-uuid-here', '1000');

Currency Rebalancing

Automatically rebalance a portfolio by swapping between currencies when certain thresholds are met.

async function rebalancePortfolio(walletId, targetUsdcPercentage = 50) {
// 1. Get supported currencies
const currencies = await getSupportedCurrencies();
// 2. Get current exchange rates
const ethToUsdcRate = await getExchangeRate('ETH', 'USDC');
// 3. Check current balances (simplified example - in a real app, you would query wallet balances)
const ethBalance = 10; // Example: 10 ETH
const usdcBalance = 10000; // Example: 10,000 USDC
// 4. Calculate total portfolio value in USDC
const totalValueInUsdc = usdcBalance + (ethBalance * parseFloat(ethToUsdcRate.rate));
// 5. Calculate current USDC percentage
const currentUsdcPercentage = (usdcBalance / totalValueInUsdc) * 100;
console.log(`Current portfolio: ${ethBalance} ETH and ${usdcBalance} USDC`);
console.log(`Current USDC percentage: ${currentUsdcPercentage.toFixed(2)}%`);
console.log(`Target USDC percentage: ${targetUsdcPercentage}%`);
// 6. Determine if rebalancing is needed (using a 5% threshold)
if (Math.abs(currentUsdcPercentage - targetUsdcPercentage) > 5) {
console.log("Rebalancing needed");
// 7. Calculate the amount to swap
const targetUsdcValue = totalValueInUsdc * (targetUsdcPercentage / 100);
const usdcDifference = targetUsdcValue - usdcBalance;
if (usdcDifference > 0) {
// Need more USDC, convert from ETH
const ethToConvert = usdcDifference / parseFloat(ethToUsdcRate.rate);
console.log(`Converting ${ethToConvert.toFixed(6)} ETH to USDC`);
// Execute swap
await initiateSwap('ETH', 'USDC', ethToConvert.toString(), walletId);
} else {
// Need less USDC, convert to ETH
const usdcToConvert = Math.abs(usdcDifference);
console.log(`Converting ${usdcToConvert.toFixed(2)} USDC to ETH`);
// Execute swap
await initiateSwap('USDC', 'ETH', usdcToConvert.toString(), walletId);
}
} else {
console.log("No rebalancing needed");
}
}
// Example usage
rebalancePortfolio('wallet-uuid-here', 60);

Best Practices

When working with the Swap Service, consider these best practices:

  1. Always check rates before swapping - Exchange rates can fluctuate rapidly, so get a fresh rate quote before initiating a swap.

  2. Verify supported currencies - Make sure both the source and destination currencies are supported before attempting a swap.

  3. Monitor transaction status - Always check the status of a swap transaction to confirm it completed successfully.

  4. Consider transaction size - Large swaps may get split across multiple liquidity sources or take longer to complete.

  5. Keep records of transaction IDs - Store transaction IDs for future reference and troubleshooting.

  6. Handle errors gracefully - Implement proper error handling for failed swaps, including user-friendly error messages.

  7. Use organization-level filtering - For applications managing multiple wallets, use organization-level filtering to track all swaps across the organization.

Troubleshooting

Common Issues

IssuePossible CausesSolutions
Swap fails to initiateInsufficient balance, unsupported currencyCheck wallet balance, verify currency support
Swap remains in pending stateLiquidity issues, network congestionWait for resolution, check status periodically
Rate discrepancyMarket volatility, stale quotesAlways get fresh quotes before swapping
Transaction not foundInvalid transaction ID, incorrect API credentialsVerify transaction ID, check API permissions

Error Handling

Implement robust error handling in your code:

try {
const swapResult = await initiateSwap('USDC', 'ETH', '1000', 'wallet-uuid-here');
// Process successful result
} catch (error) {
if (error.response) {
const errorData = await error.response.json();
if (error.response.status === 400) {
console.error("Bad request:", errorData.message);
// Handle validation errors
} else if (error.response.status === 401) {
console.error("Authentication error");
// Handle authentication issues
} else {
console.error("API error:", errorData);
// Handle other API errors
}
} else {
console.error("Network error:", error.message);
// Handle network/connection issues
}
}

Next Steps

Now that you understand how to use the Swap Service, consider exploring: