// SPDX-FileCopyrightText: © 2024 LEDGER SAS // SPDX-License-Identifier: Apache-2.0 import type { Context, CurrencyConfig } from '../../config' import type { CoinModuleApi, Memo, MemoNotSupported, TxData, TxDataNotSupported } from '../types' import { instrumentApi } from './instrumenter' /** * Wraps a {@link CoinModuleApi} to emit log entries via the per-call {@link Context}'s * logger before and after each method invocation, including on error. * * The Context is forwarded unchanged to the underlying method. * Handles both synchronous methods (e.g. `combine`) and async methods uniformly. */ export function withLogging< C extends CurrencyConfig, M extends Memo = MemoNotSupported, T extends TxData = TxDataNotSupported, Extra extends object = Record, >(api: CoinModuleApi & Extra): CoinModuleApi & Extra { return instrumentApi(api, (name, fn, args) => { // oxlint-disable-next-line consistent-type-assertions -- args[0] is always Context per CoinModuleApi contract; unknown cast needed to access logger const logger = (args[0] as Context | undefined)?.logger logger?.(`[coin-module] ${name}: call`) let result: unknown try { result = fn(...args) } catch (e) { logger?.(`[coin-module] ${name}: error`, e) throw e } if (result instanceof Promise) { return result.then( (v) => { logger?.(`[coin-module] ${name}: ok`) return v }, (e) => { logger?.(`[coin-module] ${name}: error`, e) throw e } ) } logger?.(`[coin-module] ${name}: ok`) return result }) }