import { AxiosStatic } from "axios" ; import { Cache } from "flat-cache" ; import { assertExists , assertIsNonEmptyString } from "." ; import { Trace } from "../../sdk/trace" ; export type GetTraceData = ( blockNumberOrTxHash : number | string ) => Promise < Trace [ ] > ; export function provideGetTraceData ( traceRpcUrl , traceBlockMethod , traceTransactionMethod , axios , cache ) { assertIsNonEmptyString ( traceBlockMethod , 'traceBlockMethod' ) ; assertIsNonEmptyString ( traceTransactionMethod , 'traceTransactionMethod' ) ; assertExists ( axios , 'axios' ) ; assertExists ( cache , 'cache' ) ; return async function getTraceData ( blockNumberOrTxHash ) { if ( ! traceRpcUrl ?. length ) return [ ] ; const cacheKey = getCacheKey ( blockNumberOrTxHash ) ; const cachedTraceData = cache . getKey ( cacheKey ) ; if ( cachedTraceData ) return cachedTraceData ; const isBlockNumber = typeof blockNumberOrTxHash === 'number' ; try { const { data } = await axios . post ( traceRpcUrl , { method : isBlockNumber ? traceBlockMethod : traceTransactionMethod , params : isBlockNumber ? [ `0x${ blockNumberOrTxHash . toString ( 16 ) }` ] : [ blockNumberOrTxHash ] , jsonrpc : "2.0" , id : Date . now ( ) , } , { headers : { "Content-Type" : "application/json" , } } ) ; if ( data . error ) throw new Error ( data . error . message ) ; if ( ! data . result ) throw new Error ( `unknown ${ isBlockNumber ? 'block' : 'transaction' } ${ blockNumberOrTxHash }` ) ; cache . setKey ( cacheKey , data . result ) ; return data . result ; } catch ( e ) { console . log ( `error getting trace data: ${ e . message }` ) ; } return [ ] ; } ; } export const getCacheKey = ( blockNumberOrTxHash ) => `${ blockNumberOrTxHash . toString ( ) . toLowerCase ( ) }-trace` ;