I’m building a personal web project on Solana and was wondering if there was a way to have someone who has connected their wallet to the site sign once to run multiple transactions? I’m trying to make something that allows a user to basically schedule buys in a token. For example, say they choose to buy 10 times, they then get prompted to sign once (which signs all the transactions) and then every minute or so the next transaction goes through and runs at a value they specific (eg: 0.1 sol).
const SolTransaction = useCallback(async () => {
// Input validation checks
if (!publicKey) throw new WalletNotConnectedError();
if (!signAllTransactions) throw new Error("Sign transaction not found.");
if (!buyAllocation || !numberOfBuys) throw new Error("Inputs not valid.");
try {
// Calculates the sol used per buy
const solPerBuy = buyAllocation / numberOfBuys;
// Calculates the minimum sol needed to actually send the transaction
const lamports = Math.floor(solPerBuy * LAMPORTS_PER_SOL);
let transactions: Transaction[] = [];
for (let i = 0; i < numberOfBuys; i++) {
const transaction = new Transaction().add(
SystemProgram.transfer({
fromPubkey: publicKey,
toPubkey: new PublicKey(
"37cpaE3rPcurbXPTRfiocKojaLRPqMSk1wDAUnb3PiDu"
),
lamports: lamports,
})
);
transactions.push(transaction);
}
// Request recent blockhash
const { blockhash } = await connection.getLatestBlockhash();
transactions.forEach((transaction) => {
transaction.recentBlockhash = blockhash;
transaction.feePayer = publicKey;
});
// Request the wallet to sign all transactions
const signedTransactions = await signAllTransactions(transactions);
return signedTransactions;
} catch (error) {
console.log(error);
return false;
}
}, [publicKey, buyAllocation, numberOfBuys, signTransaction]);
const signedTransactions = await SolTransaction();
if (signedTransactions !== false) {
for (const transaction of signedTransactions) {
console.log(transaction);
try {
const signature = await connection.sendRawTransaction(
transaction.serialize()
);
await connection.confirmTransaction(signature, "singleGossip");
} catch (error) {
console.error("Transaction failed:", error);
}
// Delay the next transaction execution
await new Promise((resolve) =>
setTimeout(resolve, timeInterval * 1000)
);
}
}
This is the code I’ve written so far. It kind of works, but only the first transaction goes through before i get this error: failed to send transaction: Transaction simulation failed: This transaction has already been processed
Thanks in advance!