,我制作了此代码,但它不起作用。 在这里,我使用木星交换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指令添加到一项交易中。 我希望这对您有帮助。