MCPcopy Create free account
hub / github.com/0xProject/0x-examples / executeSwap

Function executeSwap

solana-example/src/index.ts:98–175  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

96
97// === Step 4: Execute Swap with Simulation and Confirmation ===
98async function executeSwap() {
99 try {
100 const quote = await getQuote();
101 console.log(`💰 Quote received: ${quote.amount_out} base units of USDC`);
102
103 const instructions = buildInstructions(quote.instructions);
104 const [addressLookupTableAccounts, latestBlockhash] = await Promise.all([
105 resolveAddressLookupTables(quote.address_lookup_tables ?? []),
106 config.connection.getLatestBlockhash(),
107 ]);
108
109 const messageV0 = new TransactionMessage({
110 payerKey: config.keypairConfig.keypair.publicKey,
111 recentBlockhash: latestBlockhash.blockhash,
112 instructions,
113 }).compileToV0Message(addressLookupTableAccounts);
114
115 const versionedTx = new VersionedTransaction(messageV0);
116 versionedTx.sign([config.keypairConfig.keypair]);
117
118 if (!config.keypairConfig.isUserProvided) {
119 console.log(
120 "No private key provided. Please provide a private key to enable simulation and transaction sending."
121 );
122 return;
123 }
124
125 // === Simulate Transaction ===
126 const { value: simulationResult } =
127 await config.connection.simulateTransaction(versionedTx, {
128 sigVerify: true,
129 });
130
131 if (simulationResult.err) {
132 console.error("❌ Simulation failed:", simulationResult.err);
133 if (simulationResult.logs) {
134 console.error("🪵 Logs:\n" + simulationResult.logs.join("\n"));
135 }
136 throw new Error("Aborting due to failed simulation.");
137 } else {
138 console.log("✅ Simulation succeeded");
139 }
140
141 if (config.dryRun) {
142 console.log("🏁 Dry run complete. Set DRY_RUN=false to send the transaction.");
143 return;
144 }
145
146 // === Send Transaction ===
147 const signature = await config.connection.sendTransaction(versionedTx, {
148 skipPreflight: false,
149 });
150
151 console.log(`✍️ Transaction sent with signature: ${signature}`);
152
153 // === Confirm Transaction Status ===
154 const confirmation = await config.connection.confirmTransaction(
155 {

Callers 1

index.tsFile · 0.70

Calls 3

getQuoteFunction · 0.85
buildInstructionsFunction · 0.85

Tested by

no test coverage detected