2022-08-12 17:15:12 -07:00
|
|
|
import { AnchorProvider } from '@project-serum/anchor';
|
|
|
|
import { Transaction } from '@solana/web3.js';
|
|
|
|
|
|
|
|
export async function sendTransaction(
|
|
|
|
provider: AnchorProvider,
|
|
|
|
transaction: Transaction,
|
|
|
|
opts: any = {},
|
|
|
|
) {
|
|
|
|
const connection = provider.connection;
|
|
|
|
const payer = provider.wallet;
|
2022-09-05 14:36:42 -07:00
|
|
|
const latestBlockhash = await connection.getLatestBlockhash(
|
|
|
|
opts.preflightCommitment,
|
|
|
|
);
|
|
|
|
transaction.recentBlockhash = latestBlockhash.blockhash;
|
|
|
|
transaction.lastValidBlockHeight = latestBlockhash.lastValidBlockHeight;
|
2022-08-12 17:15:12 -07:00
|
|
|
transaction.feePayer = payer.publicKey;
|
2022-08-15 22:08:25 -07:00
|
|
|
if (opts.additionalSigners?.length > 0) {
|
2022-08-15 22:04:14 -07:00
|
|
|
transaction.partialSign(...opts.additionalSigners);
|
|
|
|
}
|
2022-08-12 17:15:12 -07:00
|
|
|
|
|
|
|
await payer.signTransaction(transaction);
|
|
|
|
const rawTransaction = transaction.serialize();
|
|
|
|
|
|
|
|
const signature = await connection.sendRawTransaction(rawTransaction, {
|
|
|
|
skipPreflight: true,
|
|
|
|
});
|
|
|
|
|
|
|
|
if (opts.postSendTxCallback) {
|
|
|
|
try {
|
|
|
|
opts.postSendTxCallback({ txid: signature });
|
|
|
|
} catch (e) {
|
|
|
|
console.warn(`postSendTxCallback error ${e}`);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-08-26 12:42:10 -07:00
|
|
|
let status: any;
|
|
|
|
if (
|
2022-08-12 17:15:12 -07:00
|
|
|
transaction.recentBlockhash != null &&
|
|
|
|
transaction.lastValidBlockHeight != null
|
2022-08-26 12:42:10 -07:00
|
|
|
) {
|
|
|
|
console.log('confirming via blockhash');
|
|
|
|
status = (
|
|
|
|
await connection.confirmTransaction(
|
|
|
|
{
|
|
|
|
signature: signature,
|
|
|
|
blockhash: transaction.recentBlockhash,
|
|
|
|
lastValidBlockHeight: transaction.lastValidBlockHeight,
|
|
|
|
},
|
|
|
|
'processed',
|
|
|
|
)
|
|
|
|
).value;
|
|
|
|
} else {
|
|
|
|
console.log('confirming via timeout');
|
|
|
|
status = (await connection.confirmTransaction(signature, 'processed'))
|
|
|
|
.value;
|
|
|
|
}
|
2022-08-12 17:15:12 -07:00
|
|
|
|
|
|
|
if (status.err) {
|
|
|
|
throw new MangoError({
|
|
|
|
txid: signature,
|
|
|
|
message: `Transaction ${signature} failed (${JSON.stringify(status)})`,
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
return signature;
|
|
|
|
}
|
|
|
|
|
|
|
|
class MangoError extends Error {
|
|
|
|
message: string;
|
|
|
|
txid: string;
|
|
|
|
|
|
|
|
constructor({ txid, message }) {
|
|
|
|
super();
|
|
|
|
this.message = message;
|
|
|
|
this.txid = txid;
|
|
|
|
}
|
|
|
|
}
|