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:
- You need a valid API key with appropriate permissions
- Understand the currencies you want to swap between
- 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 usagegetExchangeRate('USDC', 'ETH').then(data => { console.log(`Current rate: ${data.rate}`);});
import requests
def get_exchange_rate(source_currency, destination_currency): url = f"https://api.fsco.io/v2/swap/rate/{source_currency}/{destination_currency}" headers = { "Authorization": "Bearer YOUR_API_KEY" }
response = requests.get(url, headers=headers) data = response.json() print(f"Exchange rate: 1 {source_currency} = {data['rate']} {destination_currency}") return data
# Example usagerate_data = get_exchange_rate('USDC', 'ETH')print(f"Current rate: {rate_data['rate']}")
curl -X GET "https://api.fsco.io/v2/swap/rate/USDC/ETH" \ -H "Authorization: Bearer YOUR_API_KEY"
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 usageinitiateSwap('USDC', 'ETH', '1000', 'wallet-uuid-here').then(result => { console.log(`Track your swap with transaction ID: ${result.queryId}`);});
import requestsimport json
def initiate_swap(source_currency, destination_currency, amount, wallet_id): url = "https://api.fsco.io/v2/swap/initiate" headers = { "Content-Type": "application/json", "Authorization": "Bearer YOUR_API_KEY" } payload = { "sourceCurrency": source_currency, "destinationCurrency": destination_currency, "amount": amount, "walletId": wallet_id }
response = requests.post(url, headers=headers, json=payload) result = response.json() print(f"Swap initiated with transaction ID: {result['queryId']}") return result
# Example usageresult = initiate_swap('USDC', 'ETH', '1000', 'wallet-uuid-here')print(f"Track your swap with transaction ID: {result['queryId']}")
curl -X POST "https://api.fsco.io/v2/swap/initiate" \ -H "Content-Type: application/json" \ -H "Authorization: Bearer YOUR_API_KEY" \ -d '{ "sourceCurrency": "USDC", "destinationCurrency": "ETH", "amount": "1000", "walletId": "wallet-uuid-here" }'
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 usagegetSwapTransaction('123e4567-e89b-12d3-a456-426614174000').then(transaction => { console.log(`Swap details:`, transaction);});
import requests
def get_swap_transaction(transaction_id): url = f"https://api.fsco.io/v2/swap/transaction/{transaction_id}" headers = { "Authorization": "Bearer YOUR_API_KEY" }
response = requests.get(url, headers=headers) transaction = response.json() print(f"Swap status: {transaction['status']}") return transaction
# Example usagetransaction = get_swap_transaction('123e4567-e89b-12d3-a456-426614174000')print("Swap details:", transaction)
curl -X GET "https://api.fsco.io/v2/swap/transaction/123e4567-e89b-12d3-a456-426614174000" \ -H "Authorization: Bearer YOUR_API_KEY"
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 usagegetSwapTransactions('wallet-uuid-here', null, 'completed').then(result => { console.log(`Total pages: ${result.meta.totalPages}`); console.log(`Transactions:`, result.transactions);});
import requests
def get_swap_transactions(wallet_id=None, organisation_id=None, status=None, page=1, page_size=10): url = f"https://api.fsco.io/v2/swap/transactions?page={page}&pageSize={page_size}"
if wallet_id: url += f"&walletId={wallet_id}" if organisation_id: url += f"&organisationId={organisation_id}" if status: url += f"&status={status}"
headers = { "Authorization": "Bearer YOUR_API_KEY" }
response = requests.get(url, headers=headers) result = response.json() print(f"Found {len(result['transactions'])} transactions") return result
# Example usageresult = get_swap_transactions(wallet_id='wallet-uuid-here', status='completed')print(f"Total pages: {result['meta']['totalPages']}")print("Transactions:", result['transactions'])
curl -X GET "https://api.fsco.io/v2/swap/transactions?page=1&pageSize=10&walletId=wallet-uuid-here&status=completed" \ -H "Authorization: Bearer YOUR_API_KEY"
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 usagegetSupportedCurrencies().then(currencies => { const stablecoins = currencies.filter(c => c.isStablecoin); console.log(`Supported stablecoins: ${stablecoins.map(c => c.code).join(', ')}`);});
import requests
def get_supported_currencies(): url = "https://api.fsco.io/v2/swap/supported-currencies" headers = { "Authorization": "Bearer YOUR_API_KEY" }
response = requests.get(url, headers=headers) currencies = response.json() print(f"Found {len(currencies)} supported currencies") return currencies
# Example usagecurrencies = get_supported_currencies()stablecoins = [c for c in currencies if c['isStablecoin']]print(f"Supported stablecoins: {', '.join([c['code'] for c in stablecoins])}")
curl -X GET "https://api.fsco.io/v2/swap/supported-currencies" \ -H "Authorization: Bearer YOUR_API_KEY"
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 usageconvertStablecoinToCrypto('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 usagerebalancePortfolio('wallet-uuid-here', 60);
Best Practices
When working with the Swap Service, consider these best practices:
-
Always check rates before swapping - Exchange rates can fluctuate rapidly, so get a fresh rate quote before initiating a swap.
-
Verify supported currencies - Make sure both the source and destination currencies are supported before attempting a swap.
-
Monitor transaction status - Always check the status of a swap transaction to confirm it completed successfully.
-
Consider transaction size - Large swaps may get split across multiple liquidity sources or take longer to complete.
-
Keep records of transaction IDs - Store transaction IDs for future reference and troubleshooting.
-
Handle errors gracefully - Implement proper error handling for failed swaps, including user-friendly error messages.
-
Use organization-level filtering - For applications managing multiple wallets, use organization-level filtering to track all swaps across the organization.
Troubleshooting
Common Issues
Issue | Possible Causes | Solutions |
---|---|---|
Swap fails to initiate | Insufficient balance, unsupported currency | Check wallet balance, verify currency support |
Swap remains in pending state | Liquidity issues, network congestion | Wait for resolution, check status periodically |
Rate discrepancy | Market volatility, stale quotes | Always get fresh quotes before swapping |
Transaction not found | Invalid transaction ID, incorrect API credentials | Verify 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:
- Liquidity Management for adding liquidity to pools
- Asset Management for broader asset functionality
- Wallet Management for managing wallets and balances