default-transaction-executor.ts 1.4 KB

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