import execa from 'execa' ; import fs from 'fs' ; import tempWrite from 'temp-write' ; import { Logger } from 'fastify' ; export interface CardanoCli { param signedTransaction param isMainnet submitTransaction ( logger , signedTransaction , isMainnet ) : Promise < void > ; } export const SUPPORTED_ERAS = [ 'Tx AlonzoEra' , 'Tx MaryEra' , 'Tx AllegraEra' , 'TxSignedShelley' ] ; const wrongErraDetectRegex = /The era of the node and the tx do not match|DecoderErrorDeserialiseFailure/ ; param errorMessage const isWrongEra = ( errorMessage ) : boolean => errorMessage . match ( wrongErraDetectRegex ) !== null ; export type ProcessExecutorResult = execa . ExecaChildProcess ; export type ProcessExecutor = ( file : string , arguments_ ? : readonly string [ ] ) => ProcessExecutorResult ; const defaultExecutor = ( file , arguments_ ) => execa ( file , arguments_ ) ; export const configure = ( cardanoCliPath , networkMagic , processExecutor = defaultExecutor ) : CardanoCli => ( { async submitTransaction ( logger , signedTransaction , isMainnet ) { for ( const era of SUPPORTED_ERAS ) { logger . debug ( `[submitTransaction] About to create temp file for transaction ${ signedTransaction }` ) ; const cardanoCliFileContent = `{
        "type": "${ era }",
        "description": "",
        "cborHex": "${ signedTransaction }"
      }` ; logger . debug ( cardanoCliFileContent , '[submitTransaction] cardano-cli file' ) ; const file = await tempWrite ( cardanoCliFileContent ) ; logger . debug ( `[submitTransaction] File created at ${ file }` ) ; try { logger . debug ( `[submitTransaction] Invoking cardano-cli at ${ cardanoCliPath } using ${ networkMagic } networkMagic` ) ; const commonParameters = [ 'transaction' , 'submit' , '--tx-file' , file ] ; const parameters = isMainnet ? commonParameters . concat ( '--mainnet' ) : commonParameters . concat ( '--testnet-magic' , networkMagic . toString ( ) ) ; const { stdout } = await processExecutor ( cardanoCliPath , parameters ) ; logger . info ( '[submitTransaction] transaction successfully sent' , stdout . toString ( ) ) ; return ; } catch ( error ) { logger . error ( error , '[submitTransaction] Command failed' ) ; if ( isWrongEra ( error . stderr . toString ( ) ) ) { logger . debug ( `[submitTransaction] Era mismatch when using era ${ era }` ) ; } else { throw new Error ( error . stderr . toString ( ) ) ; } } finally { await fs . promises . unlink ( file ) ; } } throw new Error ( 'Transaction not submitted. Era not supported.' ) ; } } ) ;