import { Connection, PublicKey, VersionedTransaction } from '@solana/web3.js';
const API_URL = 'https://api.delora.build/v1';
const SOLANA_RPC_URL = 'https://solana-rpc.publicnode.com';
interface SolanaProvider {
publicKey: PublicKey;
signTransaction: (transaction: VersionedTransaction) => Promise<VersionedTransaction>;
connect: () => Promise<{ publicKey: PublicKey }>;
}
const getQuote = async (params: {
originChainId: number;
destinationChainId: number;
amount: string;
originCurrency: string;
destinationCurrency: string;
tradeType: 'EXACT_INPUT' | 'EXACT_OUTPUT';
senderAddress?: string;
receiverAddress?: string;
}) => {
const query = new URLSearchParams();
for (const [key, value] of Object.entries(params)) {
if (value !== undefined) {
query.append(key, String(value));
}
}
const url = `${API_URL}/quotes?${query.toString()}`;
const response = await fetch(url);
if (!response.ok) {
throw new Error(`Failed to get quote: ${response.status} ${response.statusText}`);
}
return response.json();
};
export const executeSwap = async (provider: SolanaProvider, connection: Connection) => {
await provider.connect();
const walletAddress = provider.publicKey.toString();
const originChainId = 1000000001;
const destinationChainId = 1000000001;
const originCurrency: string = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';
const destinationCurrency = 'Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB';
const amount = (100 * 1e6).toString();
const quote = await getQuote({
originChainId,
destinationChainId,
amount,
originCurrency,
destinationCurrency,
tradeType: 'EXACT_INPUT',
senderAddress: walletAddress,
receiverAddress: walletAddress,
});
if (!quote.calldata?.data) {
throw new Error('Transaction data is missing in quote response');
}
const transactionBuffer = Uint8Array.from(atob(quote.calldata.data), c => c.charCodeAt(0));
let transaction: VersionedTransaction;
try {
transaction = VersionedTransaction.deserialize(transactionBuffer);
} catch (error: any) {
throw new Error(`Failed to deserialize transaction: ${error.message}`);
}
const signedTransaction = await provider.signTransaction(transaction);
const signature = await connection.sendRawTransaction(signedTransaction.serialize(), {
skipPreflight: false,
maxRetries: 3,
});
const latestBlockhash = await connection.getLatestBlockhash('confirmed');
const confirmation = await connection.confirmTransaction({
signature,
blockhash: latestBlockhash.blockhash,
lastValidBlockHeight: latestBlockhash.lastValidBlockHeight,
}, 'confirmed');
if (confirmation.value.err) {
throw new Error(`Transaction failed: ${JSON.stringify(confirmation.value.err)}`);
}
return signature;
};