import { Injectable } from '@angular/core' ; import { TransactionOverlayComponent } from './transaction-overlay.component' ; import { Subscription } from 'rxjs' ; @ Injectable ( { providedIn : 'root' } ) export class TransactionOverlayService { private comp : TransactionOverlayComponent ; setComponent ( comp ) { this . comp = comp ; } waitForSetupMetaMask ( ) { const compEventEmitter = this . comp . show ( this . comp . COMP_SETUP_METAMASK ) ; return new Promise ( ( resolve , reject ) => { const subscription = compEventEmitter . subscribe ( data => { subscription . unsubscribe ( ) ; if ( data && ! ( data instanceof Error ) ) { resolve ( data ) ; } else { reject ( ( data && data . message ) || 'User cancelled' ) ; } } ) ; } ) ; } waitForAccountUnlock ( ) { let compEventEmitter = this . comp . show ( this . comp . COMP_UNLOCK ) ; return new Promise ( ( resolve , reject ) => { let subscription = compEventEmitter . subscribe ( data => { subscription . unsubscribe ( ) ; if ( data && ! ( data instanceof Error ) ) { resolve ( data ) ; } else { reject ( ( data && data . message ) || 'User cancelled' ) ; } } ) ; } ) ; } waitForLocalTxObject ( defaultTxObject = { } , message = '' , tokenDelta = 0 ) { let compEventEmitter = this . comp . show ( this . comp . COMP_LOCAL , message , defaultTxObject , { tokenDelta } ) ; return new Promise ( ( resolve , reject ) => { let subscription = compEventEmitter . subscribe ( data => { subscription . unsubscribe ( ) ; if ( data && ! ( data instanceof Error ) ) { resolve ( data ) ; } else { reject ( data || new Error ( 'User cancelled' ) ) ; } } ) ; } ) ; } async waitForExternalTx ( fn , message = '' ) { this . comp . show ( this . comp . COMP_METAMASK , message ) ; let result = null ; try { result = await fn ( ) ; } catch ( e ) { if ( e . value && e . value . message && e . value . message . includes ( 'User denied transaction signature' ) ) { throw new Error ( 'User denied the transaction' ) ; } else { console . error ( e ) ; throw new Error ( 'Unexpected error. Is your wallet unlocked?' ) ; } } finally { this . comp . hide ( ) ; } return result . hash ; } }