// Minimal swap implementation
class SoroswapClient {
constructor(apiKey, network = 'testnet') {
this.apiKey = apiKey;
this.network = network;
this.baseUrl = 'https://api.soroswap.finance';
}
async apiRequest(endpoint, data) {
const response = await fetch(`${this.baseUrl}${endpoint}?network=${this.network}`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${this.apiKey}`,
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
});
if (!response.ok) {
const error = await response.json();
throw new Error(`API Error: ${error.message}`);
}
return response.json();
}
// 1. Get best price quote
async getQuote(assetIn, assetOut, amount, tradeType = 'EXACT_IN') {
return this.apiRequest('/quote', {
assetIn,
assetOut,
amount,
tradeType,
protocols: ['soroswap', 'phoenix', 'aqua']
});
}
// 2. Build transaction from quote
async buildTransaction(quote, fromAddress, toAddress = fromAddress) {
return this.apiRequest('/quote/build', {
quote,
from: fromAddress,
to: toAddress
});
}
// 3. Submit signed transaction
async sendTransaction(signedXdr) {
return this.apiRequest('/send', {
xdr: signedXdr
});
}
}
// Usage Example
const client = new SoroswapClient('sk_your_api_key');
async function executeSwap() {
try {
// 1. Quote
const quote = await client.getQuote(
'CDLZFC3SYJYDZT7K67VZ75HPJVIEUVNIXF47ZG2FB2RMQQVU2HHGCYSC', // XLM
'CBBHRKEP5M3NUDRISGLJKGHDHX3DA2CN2AZBQY6WLVUJ7VNLGSKBDUCM', // USDC
'10000000' // 1 XLM
);
// 2. Build
const { xdr } = await client.buildTransaction(quote, userAddress);
// 3. Sign (using your preferred wallet)
const signedXdr = await signWithWallet(xdr);
// 4. Send
const result = await client.sendTransaction(signedXdr);
console.log('Swap completed!', result.txHash);
} catch (error) {
console.error('Swap failed:', error);
}
}