You have to first use the @solana/web3.js
library to create a transaction in backend, add appropriate instructions, sign it if needed using local keypair, then encode it in base58/base64, send it to frontend, then frontend will load the base58/base64 string into a Transaction
object, and then sign it and send it. Here is how you can achieve this:
First, create a backend transaction creation handler API, something like this:
export const createTx = async () => {
let tx = new Transaction();
// Add instructions
const { blockhash } = await new Connection("rpc").getLatestBlockhash();
const kp = Keypair.fromSecretKey("your_secret"key); // If you need backend sign, loading local kp and sign tx
tx.recentBlockhash = blockhash;
const serialized = tx.serialize({ requireAllSignatures: false });
return {"transaction": bs58.encode(serialized)} // API response
};
Now, make a call to this API, which will return your encoded transaction. In your frontend, you have to load it and request signing it now, here is how:
const res = await fetch("api_url")
const data = await res.json()
const tx = Transaction.from(base58.decode(data.transaction))
tx.feePayer = wallet.publicKey
signedTx = await wallet.sign(tx)
const txSignature = await sendAndConfirmTransaction(connection, tx);