tsCopiarEditarimport {
Connection, PublicKey, TransactionInstruction, TransactionMessage,
VersionedTransaction, AddressLookupTableAccount
} from '@solana/web3.js';
// 1️⃣ Initialize Solana connection
const connection = new Connection('https://api.mainnet-beta.solana.com');
// 2️⃣ Function to create and send a transaction
async function sendSolanaTransaction(wallet, instructionsData, addressLookupTableAccounts) {
if (!wallet?.publicKey) {
throw new Error("Wallet is not connected");
}
// 3️⃣ Convert instruction data into TransactionInstructions
const instructions = instructionsData.map((instruction) => new TransactionInstruction({
keys: instruction.keys.map(key => ({
pubkey: new PublicKey(key.pubkey),
isSigner: key.isSigner,
isWritable: key.isWritable
})),
programId: new PublicKey(instruction.programId),
data: Buffer.from(instruction.data)
}));
// 4️⃣ Fetch the latest blockhash
const { blockhash } = await connection.getLatestBlockhash('confirmed');
// 5️⃣ Handle Address Lookup Tables (if available)
const lookupTables = addressLookupTableAccounts?.map(alta => new AddressLookupTableAccount({
key: new PublicKey(alta.key),
state: {
addresses: alta.state.addresses.map(addr => new PublicKey(addr)),
authority: new PublicKey(alta.state.authority),
deactivationSlot: BigInt(alta.state.deactivationSlot),
lastExtendedSlot: alta.state.lastExtendedSlot,
lastExtendedSlotStartIndex: alta.state.lastExtendedSlotStartIndex
}
}));
// 6️⃣ Create a TransactionMessage
const messageV0 = new TransactionMessage({
payerKey: wallet.publicKey,
recentBlockhash: blockhash,
instructions: instructions
});
// 7️⃣ Compile to VersionedTransaction
const messageV0Compiled = messageV0.compileToV0Message(lookupTables);
const transaction = new VersionedTransaction(messageV0Compiled);
// 8️⃣ Sign and send the transaction
const signature = await wallet.signAndSendTransaction(transaction);
console.log("Transaction Signature:", signature);
return signature;
}
tsCopiarEditar// Example wallet object (Replace with actual wallet provider)
const wallet = {
publicKey: new PublicKey("YourWalletPublicKeyHere"),
signAndSendTransaction: async (tx) => {
console.log("Signing and sending transaction...");
return "mock_signature"; // Replace with actual wallet signing logic
}
};
// Example transaction instructions (Replace with real data)
const transactionInstructions = [
{
keys: [{ pubkey: "TargetAddressHere", isSigner: false, isWritable: true }],
programId: "ProgramIdHere",
data: "Base64EncodedDataHere"
}
];
// Example Address Lookup Tables (Replace with real ALTs)
const addressLookupTableAccounts = [];
// Send transaction
sendSolanaTransaction(wallet, transactionInstructions, addressLookupTableAccounts)
.then(sig => console.log("Transaction sent with signature:", sig))
.catch(err => console.error("Transaction failed:", err));