default-transaction-executor.ts 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. import {
  2. BlockhashWithExpiryBlockHeight,
  3. Connection,
  4. Keypair,
  5. Transaction,
  6. VersionedTransaction,
  7. } from '@solana/web3.js';
  8. import { TransactionExecutor } from './transaction-executor.interface';
  9. import { logger } from '../helpers';
  10. export class DefaultTransactionExecutor implements TransactionExecutor {
  11. constructor(private readonly connection: Connection) {}
  12. public async executeAndConfirm(
  13. transaction: VersionedTransaction,
  14. payer: Keypair,
  15. latestBlockhash: BlockhashWithExpiryBlockHeight,
  16. ): Promise<{ confirmed: boolean; signature?: string, error?: string }> {
  17. logger.debug('Executing transaction...');
  18. const signature = await this.execute(transaction);
  19. logger.debug({ signature }, 'Confirming transaction...');
  20. return this.confirm(signature, latestBlockhash);
  21. }
  22. private async execute(transaction: Transaction | VersionedTransaction) {
  23. return this.connection.sendRawTransaction(transaction.serialize(), {
  24. preflightCommitment: this.connection.commitment,
  25. });
  26. }
  27. private async confirm(signature: string, latestBlockhash: BlockhashWithExpiryBlockHeight) {
  28. const confirmation = await this.connection.confirmTransaction(
  29. {
  30. signature,
  31. lastValidBlockHeight: latestBlockhash.lastValidBlockHeight,
  32. blockhash: latestBlockhash.blockhash,
  33. },
  34. this.connection.commitment,
  35. );
  36. return { confirmed: !confirmation.value.err, signature };
  37. }
  38. }