如何将交换说明和转索尔指令添加到solana中的一项交易?

问题描述 投票:0回答:0
我想在发生交易交易时将一些溶胶作为费用转移到特定的钱包中。

,我制作了此代码,但它不起作用。 在这里,我使用木星交换API交换令牌。 我将我的Transfersol指令添加到交易交易中。

请帮助我 thanks.

const connection = new Connection(RPC_URL, "confirmed"); const tokenDecimals = await getTokenDecimals(connection, tokenAddress); const slippageBps = parseInt(process.env.SLIPPAGEBPS || "") || 50; let swapInfo: any; swapInfo = await getSwapInfo( NATIVE_MINT.toBase58(), tokenAddress, amount * LAMPORTS_PER_SOL, slippageBps ); const swapTransaction = await getSwapTransaction(swapInfo, anchorWallet); const swapTransactionBuf = Buffer.from(swapTransaction, "base64"); const latestBlockHash = await connection.getLatestBlockhash(); const versionedTransaction = VersionedTransaction.deserialize(swapTransactionBuf); const transferInstruction = SystemProgram.transfer({ fromPubkey: sender.publicKey, toPubkey: receiverPublicKey, lamports: 0.01 * LAMPORTS_PER_SOL, }); // Extract existing instructions from the versioned transaction const existingInstructions = versionedTransaction.message.instructions; // Add the transfer instruction to the list of instructions const updatedInstructions = [...existingInstructions, transferInstruction]; // Reconstruct the message with the updated instructions const updatedMessage = new TransactionMessage({ payerKey: anchorWallet.payer.publicKey, recentBlockhash: latestBlockHash.blockhash, instructions: updatedInstructions, }); // Create a new VersionedTransaction with the updated message const updatedTransaction = new VersionedTransaction(updatedMessage); // Sign the updated transaction updatedTransaction.sign([anchorWallet.payer]);

这些是木星API函数。

const JUP_API = "https://quote-api.jup.ag/v6"; export const getSwapInfo = async (tokenA: string, tokenB: string, amount: number, slippageBps: number) => { const res = await axios.get(`${JUP_API}/quote?inputMint=${tokenA}&outputMint=${tokenB}&amount=${amount}&slippageBps=${slippageBps}`); const swapinfo = res.data; return swapinfo; }; export const getSwapTransaction = async (quoteResponse: any, anchorWallet: Wallet) => { const swapResponse = await axios.post(`${JUP_API}/swap`, { quoteResponse, userPublicKey: anchorWallet.publicKey.toString(), wrapAndUnwrapSol: true, prioritizationFeeLamports: 200000, // or custom lamports: 1000 }); return swapResponse.data.swapTransaction; };

您应该使用木星交换API获得交换说明,而不是交易交易。
const instructions = ( await axios.post( "https://quote-api.jup.ag/v6/swap-instructions", { quoteResponse: routeData, userPublicKey: ownerAddress, wrapAndUnwrapSol: true, computeUnitPriceMicroLamports: Math.floor(gasFee * 1e9), // ✅ Convert SOL Gas Fee to MicroLamports }, { headers: { "Content-Type": "application/json", }, } ) ).data;

将这些交换说明和您的Transfersol指令添加到一项交易中。 我希望这对您有帮助。
	
typescript swap solana solana-web3js solana-transaction-instruction
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.