import { EventEmitter } from "eventemitter3" ; import { IRPCGetTransactionReceiptResult , IRPCGetTransactionRequest , IRPCGetTransactionResult , QtumRPC , } from "./QtumRPC" ; import { sleep } from "./sleep" ; export type TxReceiptConfirmationHandler = ( tx : IRPCGetTransactionResult , receipt : IRPCGetTransactionReceiptResult ) => any ; const EVENT_CONFIRM = "confirm" ; export interface ITxReceiptConfirmOptions { pollInterval ? : number ; } export class TxReceiptPromise { private _emitter : EventEmitter ; constructor ( private _rpc , public txid ) { this . _emitter = new EventEmitter ( ) ; } public async confirm ( confirm = 6 , opts = { } ) { const minconf = confirm ; const pollInterval = opts . pollInterval || 3000 ; const hasTxWaitSupport = await this . _rpc . checkTransactionWaitSupport ( ) ; let curConfirmation = 1 ; let lastConfirmation = 0 ; while ( true ) { const req = { txid : this . txid } ; if ( hasTxWaitSupport ) { req . waitconf = curConfirmation ; } const tx = await this . _rpc . getTransaction ( req ) ; if ( tx . confirmations > 0 ) { const receipt = await this . _rpc . getTransactionReceipt ( { txid : tx . txid } ) ; if ( ! receipt ) { throw new Error ( "Cannot get transaction receipt" ) ; } const receipt2 = receipt ; if ( tx . confirmations > lastConfirmation ) { curConfirmation = tx . confirmations ; this . _emitter . emit ( EVENT_CONFIRM , tx , receipt2 ) ; } if ( tx . confirmations >= minconf ) { return receipt2 ; } } lastConfirmation = tx . confirmations ; if ( hasTxWaitSupport ) { curConfirmation ++ ; } else { await sleep ( pollInterval + Math . random ( ) * 200 ) ; } } } public onConfirm ( fn ) { this . _emitter . on ( EVENT_CONFIRM , fn ) ; } public offConfirm ( fn ) { this . _emitter . off ( EVENT_CONFIRM , fn ) ; } }