From 4c09148e4c243f9391c9b024b64e9c209746da37 Mon Sep 17 00:00:00 2001 From: Andrew Taran Date: Tue, 11 Aug 2026 12:17:31 +0200 Subject: [PATCH] chore: replace tron logger with shared util --- eslint-suppressions.json | 8 -- packages/tron-wallet-snap/.env.example | 5 + packages/tron-wallet-snap/snap.config.ts | 2 + packages/tron-wallet-snap/snap.manifest.json | 2 +- .../src/caching/InMemoryCache.ts | 6 +- .../src/caching/StateCache.test.ts | 95 +++++++++--------- .../src/caching/StateCache.ts | 6 +- .../src/clients/price-api/PriceApiClient.ts | 6 +- .../SecurityAlertsApiClient.ts | 9 +- .../src/clients/snap/SnapClient.test.ts | 31 +++--- .../src/clients/snap/SnapClient.ts | 9 +- .../src/clients/token-api/TokenApiClient.ts | 6 +- packages/tron-wallet-snap/src/context.ts | 1 + .../src/handlers/assets/assets.ts | 9 +- .../handlers/clientRequest/clientRequest.ts | 9 +- .../src/handlers/cronjob/cronjob.test.tsx | 21 +--- .../src/handlers/cronjob/cronjob.tsx | 9 +- .../src/handlers/keyring/keyring.ts | 9 +- .../tron-wallet-snap/src/handlers/rpc/rpc.ts | 9 +- .../src/handlers/user-input/userInput.ts | 9 +- .../services/accounts/AccountsService.test.ts | 6 +- .../src/services/accounts/AccountsService.ts | 9 +- .../assets/adapters/CoreAssetsAdapter.ts | 8 +- .../assets/adapters/SnapAssetsAdapter.ts | 9 +- .../src/services/config/ConfigProvider.ts | 5 + .../confirmation/ConfirmationHandler.test.ts | 2 + .../confirmation/ConfirmationHandler.ts | 9 +- .../src/services/send/FeeCalculatorService.ts | 9 +- .../src/services/send/SendService.ts | 9 +- .../src/services/staking/StakingService.ts | 9 +- .../TransactionScanService.ts | 6 +- .../transactions/TransactionsService.test.ts | 4 +- .../transactions/TransactionsService.ts | 9 +- .../src/services/wallet/WalletService.ts | 9 +- .../tron-wallet-snap/src/utils/errors.test.ts | 21 ++-- packages/tron-wallet-snap/src/utils/logger.ts | 98 +------------------ .../tron-wallet-snap/src/utils/mockLogger.ts | 21 +++- 37 files changed, 210 insertions(+), 294 deletions(-) diff --git a/eslint-suppressions.json b/eslint-suppressions.json index 9492bd3d0..ab900bafe 100644 --- a/eslint-suppressions.json +++ b/eslint-suppressions.json @@ -1330,14 +1330,6 @@ "count": 2 } }, - "packages/tron-wallet-snap/snap.config.ts": { - "import-x/no-nodejs-modules": { - "count": 1 - }, - "no-restricted-globals": { - "count": 20 - } - }, "packages/tron-wallet-snap/src/caching/StateCache.ts": { "no-restricted-syntax": { "count": 1 diff --git a/packages/tron-wallet-snap/.env.example b/packages/tron-wallet-snap/.env.example index 1444ae2f4..bd672ae6d 100644 --- a/packages/tron-wallet-snap/.env.example +++ b/packages/tron-wallet-snap/.env.example @@ -4,6 +4,11 @@ # - production before submitting a PR ENVIRONMENT=local +# Log Level +# Possible Options: error, warn, info, debug, trace, silent +# Default: info +LOG_LEVEL=silent + RPC_URL_LIST_MAINNET=https://api.trongrid.io RPC_URL_LIST_NILE_TESTNET=https://nile.trongrid.io RPC_URL_LIST_SHASTA_TESTNET=https://api.shasta.trongrid.io/jsonrpc diff --git a/packages/tron-wallet-snap/snap.config.ts b/packages/tron-wallet-snap/snap.config.ts index ed7d1ef21..abb8f37d1 100644 --- a/packages/tron-wallet-snap/snap.config.ts +++ b/packages/tron-wallet-snap/snap.config.ts @@ -1,3 +1,4 @@ +/* eslint-disable import-x/no-nodejs-modules, no-restricted-globals -- Snap configuration executes in Node.js. */ import type { SnapConfig } from '@metamask/snaps-cli'; import { config as dotenv } from 'dotenv'; import { resolve } from 'path'; @@ -11,6 +12,7 @@ const config: SnapConfig = { }, environment: { ENVIRONMENT: process.env.ENVIRONMENT ?? '', + LOG_LEVEL: process.env.LOG_LEVEL ?? '', // RPC RPC_URL_LIST_MAINNET: process.env.RPC_URL_LIST_MAINNET ?? '', RPC_URL_LIST_NILE_TESTNET: process.env.RPC_URL_LIST_NILE_TESTNET ?? '', diff --git a/packages/tron-wallet-snap/snap.manifest.json b/packages/tron-wallet-snap/snap.manifest.json index 3e41a75cf..fe36b7959 100644 --- a/packages/tron-wallet-snap/snap.manifest.json +++ b/packages/tron-wallet-snap/snap.manifest.json @@ -7,7 +7,7 @@ "url": "https://github.com/MetaMask/internal-snaps.git" }, "source": { - "shasum": "tjWVt/iPBoSqDOS1uPATvu4MiZ4mkgwuEEZlMNDAwHc=", + "shasum": "MbqwOXbHFI83/qWOj9zDSXJizgEt5oQ+QnpHq0g/sls=", "location": { "npm": { "filePath": "dist/bundle.js", diff --git a/packages/tron-wallet-snap/src/caching/InMemoryCache.ts b/packages/tron-wallet-snap/src/caching/InMemoryCache.ts index 1549b6398..e81b81443 100644 --- a/packages/tron-wallet-snap/src/caching/InMemoryCache.ts +++ b/packages/tron-wallet-snap/src/caching/InMemoryCache.ts @@ -1,6 +1,6 @@ +import type { Logger } from '@metamask/snap-networks-utils/logger'; import { assert } from '@metamask/utils'; -import type { ILogger } from '../utils/logger'; import type { Serializable } from '../utils/serialization/types'; import type { ICache } from './ICache'; import type { CacheEntry } from './types'; @@ -14,9 +14,9 @@ import type { CacheEntry } from './types'; export class InMemoryCache implements ICache { readonly #cache: Map = new Map(); - public readonly logger: ILogger; + public readonly logger: Logger; - constructor(logger: ILogger) { + constructor(logger: Logger) { this.logger = logger; } diff --git a/packages/tron-wallet-snap/src/caching/StateCache.test.ts b/packages/tron-wallet-snap/src/caching/StateCache.test.ts index 7c4b3787f..ad0037f89 100644 --- a/packages/tron-wallet-snap/src/caching/StateCache.test.ts +++ b/packages/tron-wallet-snap/src/caching/StateCache.test.ts @@ -1,12 +1,13 @@ /* eslint-disable jest/prefer-strict-equal */ import { InMemoryState } from '../services/state/InMemoryState'; +import { mockLogger } from '../utils/mockLogger'; import { StateCache } from './StateCache'; describe('StateCache', () => { describe('constructor', () => { it('uses the default prefix if not specified', () => { - const cache = new StateCache(new InMemoryState({})); + const cache = new StateCache(new InMemoryState({}), mockLogger); expect(cache.prefix).toBe('__cache__default'); }); @@ -14,7 +15,7 @@ describe('StateCache', () => { it('uses the specified prefix if provided', () => { const cache = new StateCache( new InMemoryState({}), - undefined, + mockLogger, '__cache__my-prefix', ); @@ -28,7 +29,7 @@ describe('StateCache', () => { name: 'John', // State has some data that is not related to the cache // __cache__default: {} // State has not been initialized with cached data }); - const cache = new StateCache(stateWithNoCache); + const cache = new StateCache(stateWithNoCache, mockLogger); const value = await cache.get('someKey'); @@ -44,7 +45,7 @@ describe('StateCache', () => { }, }, }); - const cache = new StateCache(stateWithCache); + const cache = new StateCache(stateWithCache, mockLogger); const value = await cache.get('someOtherKey'); @@ -60,7 +61,7 @@ describe('StateCache', () => { }, }, }); - const cache = new StateCache(stateWithCache); + const cache = new StateCache(stateWithCache, mockLogger); const value = await cache.get('someKey'); @@ -76,7 +77,7 @@ describe('StateCache', () => { }, }, }); - const cache = new StateCache(stateWithCache); + const cache = new StateCache(stateWithCache, mockLogger); const value = await cache.get('someKey'); @@ -93,7 +94,7 @@ describe('StateCache', () => { }, }, }); - const cache = new StateCache(stateWithCache); + const cache = new StateCache(stateWithCache, mockLogger); expect(await cache.get('someKey')).toBeUndefined(); }); @@ -107,7 +108,7 @@ describe('StateCache', () => { }, }, }); - const cache = new StateCache(stateWithCache); + const cache = new StateCache(stateWithCache, mockLogger); await cache.get('someKey'); const stateValue = await stateWithCache.get(); @@ -121,7 +122,7 @@ describe('StateCache', () => { describe('set', () => { it('initializes the cache if it is not initialized', async () => { const stateWithCache = new InMemoryState({}); - const cache = new StateCache(stateWithCache); + const cache = new StateCache(stateWithCache, mockLogger); await cache.set('someKey', 'someValue'); const stateValue = await stateWithCache.get(); @@ -140,7 +141,7 @@ describe('StateCache', () => { const stateWithCache = new InMemoryState({ __cache__default: {}, }); - const cache = new StateCache(stateWithCache); + const cache = new StateCache(stateWithCache, mockLogger); await cache.set('someKey', 'someValue'); const stateValue = await stateWithCache.get(); @@ -167,7 +168,7 @@ describe('StateCache', () => { }, }, }); - const cache = new StateCache(stateWithCache); + const cache = new StateCache(stateWithCache, mockLogger); await cache.set('someKey', 'someOtherValue'); const stateValue = await stateWithCache.get(); @@ -186,7 +187,7 @@ describe('StateCache', () => { const stateWithCache = new InMemoryState({ __cache__default: {}, }); - const cache = new StateCache(stateWithCache); + const cache = new StateCache(stateWithCache, mockLogger); jest.spyOn(Date, 'now').mockReturnValueOnce(1704067200000); // January 1, 2024 await cache.set('someKey', 'someValue', 1000); @@ -206,7 +207,7 @@ describe('StateCache', () => { const stateWithCache = new InMemoryState({ __cache__default: {}, }); - const cache = new StateCache(stateWithCache); + const cache = new StateCache(stateWithCache, mockLogger); const mockDateNow = jest .spyOn(Date, 'now') .mockReturnValue(1704067200000); // January 1, 2024 @@ -236,7 +237,7 @@ describe('StateCache', () => { const stateWithCache = new InMemoryState({ __cache__default: {}, }); - const cache = new StateCache(stateWithCache); + const cache = new StateCache(stateWithCache, mockLogger); await expect( cache.set('someKey', 'someValue', 'not a number' as unknown as number), @@ -247,7 +248,7 @@ describe('StateCache', () => { const stateWithCache = new InMemoryState({ __cache__default: {}, }); - const cache = new StateCache(stateWithCache); + const cache = new StateCache(stateWithCache, mockLogger); await expect(cache.set('someKey', 'someValue', -1)).rejects.toThrow( 'TTL must be positive', @@ -258,7 +259,7 @@ describe('StateCache', () => { const stateWithCache = new InMemoryState({ __cache__default: {}, }); - const cache = new StateCache(stateWithCache); + const cache = new StateCache(stateWithCache, mockLogger); await expect( cache.set('someKey', 'someValue', Number.MAX_SAFE_INTEGER + 1), @@ -276,7 +277,7 @@ describe('StateCache', () => { }, }, }); - const cache = new StateCache(stateWithCache); + const cache = new StateCache(stateWithCache, mockLogger); const result = await cache.delete('someKey'); expect(result).toBe(true); @@ -295,7 +296,7 @@ describe('StateCache', () => { }, }, }); - const cache = new StateCache(stateWithCache); + const cache = new StateCache(stateWithCache, mockLogger); const result = await cache.delete('someOtherKey'); // Try to const someKeyValue = await cache.get('someKey'); @@ -318,7 +319,7 @@ describe('StateCache', () => { }, }, }); - const cache = new StateCache(stateWithCache); + const cache = new StateCache(stateWithCache, mockLogger); await cache.clear(); const stateValue = await stateWithCache.get(); @@ -330,7 +331,7 @@ describe('StateCache', () => { it('does not throw an error if the cache is not initialized', async () => { const stateWithCache = new InMemoryState({}); - const cache = new StateCache(stateWithCache); + const cache = new StateCache(stateWithCache, mockLogger); await cache.clear(); const stateValue = await stateWithCache.get(); @@ -351,7 +352,7 @@ describe('StateCache', () => { }, }, }); - const cache = new StateCache(stateWithCache); + const cache = new StateCache(stateWithCache, mockLogger); const result = await cache.has('someKey'); @@ -367,7 +368,7 @@ describe('StateCache', () => { }, }, }); - const cache = new StateCache(stateWithCache); + const cache = new StateCache(stateWithCache, mockLogger); const result = await cache.has('someOtherKey'); expect(result).toBe(false); @@ -375,7 +376,7 @@ describe('StateCache', () => { it('does not throw an error if the cache is not initialized', async () => { const stateWithCache = new InMemoryState({}); - const cache = new StateCache(stateWithCache); + const cache = new StateCache(stateWithCache, mockLogger); const result = await cache.has('someKey'); expect(result).toBe(false); @@ -396,7 +397,7 @@ describe('StateCache', () => { }, }, }); - const cache = new StateCache(stateWithCache); + const cache = new StateCache(stateWithCache, mockLogger); const result = await cache.keys(); @@ -405,7 +406,7 @@ describe('StateCache', () => { it('returns an empty array if the cache is not initialized', async () => { const stateWithCache = new InMemoryState({}); - const cache = new StateCache(stateWithCache); + const cache = new StateCache(stateWithCache, mockLogger); const result = await cache.keys(); @@ -427,7 +428,7 @@ describe('StateCache', () => { }, }, }); - const cache = new StateCache(stateWithCache); + const cache = new StateCache(stateWithCache, mockLogger); const result = await cache.size(); @@ -436,7 +437,7 @@ describe('StateCache', () => { it('returns 0 if the cache is not initialized', async () => { const stateWithCache = new InMemoryState({}); - const cache = new StateCache(stateWithCache); + const cache = new StateCache(stateWithCache, mockLogger); const result = await cache.size(); @@ -454,7 +455,7 @@ describe('StateCache', () => { }, }, }); - const cache = new StateCache(stateWithCache); + const cache = new StateCache(stateWithCache, mockLogger); const result = await cache.peek('someKey'); @@ -470,7 +471,7 @@ describe('StateCache', () => { }, }, }); - const cache = new StateCache(stateWithCache); + const cache = new StateCache(stateWithCache, mockLogger); const result = await cache.peek('someKey'); @@ -479,7 +480,7 @@ describe('StateCache', () => { it('returns undefined if the key is not present in the cache', async () => { const stateWithCache = new InMemoryState({}); - const cache = new StateCache(stateWithCache); + const cache = new StateCache(stateWithCache, mockLogger); const result = await cache.peek('someOtherKey'); @@ -488,7 +489,7 @@ describe('StateCache', () => { it('does not throw an error if the cache is not initialized', async () => { const stateWithCache = new InMemoryState({}); - const cache = new StateCache(stateWithCache); + const cache = new StateCache(stateWithCache, mockLogger); const result = await cache.peek('someKey'); expect(result).toBeUndefined(); @@ -509,7 +510,7 @@ describe('StateCache', () => { }, }, }); - const cache = new StateCache(stateWithCache); + const cache = new StateCache(stateWithCache, mockLogger); const result = await cache.mget(['someKey', 'someOtherKey']); @@ -528,7 +529,7 @@ describe('StateCache', () => { }, }, }); - const cache = new StateCache(stateWithCache); + const cache = new StateCache(stateWithCache, mockLogger); const result = await cache.mget(['someKey', 'someOtherKey']); @@ -547,7 +548,7 @@ describe('StateCache', () => { }, }, }); - const cache = new StateCache(stateWithCache); + const cache = new StateCache(stateWithCache, mockLogger); // Mock Date.now to return a time after the expiration const mockDateNow = jest @@ -565,7 +566,7 @@ describe('StateCache', () => { it('returns an empty object if the cache is not initialized', async () => { const stateWithCache = new InMemoryState({}); - const cache = new StateCache(stateWithCache); + const cache = new StateCache(stateWithCache, mockLogger); const result = await cache.mget(['someKey', 'someOtherKey']); @@ -585,7 +586,7 @@ describe('StateCache', () => { }, }, }); - const cache = new StateCache(stateWithCache); + const cache = new StateCache(stateWithCache, mockLogger); // Mock Date.now to return a time after the expiration const mockDateNow = jest @@ -611,7 +612,7 @@ describe('StateCache', () => { describe('mset', () => { it('sets the values of the keys if they are present in the cache', async () => { const stateWithCache = new InMemoryState({}); - const cache = new StateCache(stateWithCache); + const cache = new StateCache(stateWithCache, mockLogger); await cache.mset([ { key: 'someKey', value: 'someValue' }, @@ -628,7 +629,7 @@ describe('StateCache', () => { it('does not store undefined values in the cache', async () => { const stateWithCache = new InMemoryState({}); - const cache = new StateCache(stateWithCache); + const cache = new StateCache(stateWithCache, mockLogger); await cache.mset([ { key: 'someKey', value: 'someValue' }, @@ -656,7 +657,7 @@ describe('StateCache', () => { it('stores null values in the cache', async () => { const stateWithCache = new InMemoryState({}); - const cache = new StateCache(stateWithCache); + const cache = new StateCache(stateWithCache, mockLogger); await cache.mset([{ key: 'someKey', value: null }]); @@ -669,7 +670,7 @@ describe('StateCache', () => { it('does not throw an error if the cache is not initialized', async () => { const stateWithCache = new InMemoryState({}); - const cache = new StateCache(stateWithCache); + const cache = new StateCache(stateWithCache, mockLogger); await cache.mset([{ key: 'someKey', value: 'someValue' }]); @@ -682,7 +683,7 @@ describe('StateCache', () => { it('throws an error if the ttl is invalid', async () => { const stateWithCache = new InMemoryState({}); - const cache = new StateCache(stateWithCache); + const cache = new StateCache(stateWithCache, mockLogger); await expect( cache.mset([ @@ -708,7 +709,7 @@ describe('StateCache', () => { }, }, }); - const cache = new StateCache(stateWithCache); + const cache = new StateCache(stateWithCache, mockLogger); await cache.mset([ { key: 'someKey0', value: 'someValue0Overwritten' }, @@ -726,7 +727,7 @@ describe('StateCache', () => { it('no-ops if no entries are provided', async () => { const stateWithCache = new InMemoryState({}); - const cache = new StateCache(stateWithCache); + const cache = new StateCache(stateWithCache, mockLogger); const updateSpy = jest.spyOn(stateWithCache, 'update'); await cache.mset([]); @@ -736,7 +737,7 @@ describe('StateCache', () => { it('defers to set if there is only one entry', async () => { const stateWithCache = new InMemoryState({}); - const cache = new StateCache(stateWithCache); + const cache = new StateCache(stateWithCache, mockLogger); const setSpy = jest.spyOn(cache, 'set'); const singleEntry = { @@ -768,7 +769,7 @@ describe('StateCache', () => { }, }, }); - const cache = new StateCache(stateWithCache); + const cache = new StateCache(stateWithCache, mockLogger); await cache.mdelete(['someKey', 'someOtherKey']); @@ -789,7 +790,7 @@ describe('StateCache', () => { }, }, }); - const cache = new StateCache(stateWithCache); + const cache = new StateCache(stateWithCache, mockLogger); const result = await cache.mdelete(['someKey', 'someOtherKey']); @@ -801,7 +802,7 @@ describe('StateCache', () => { it('does not throw an error if the cache is not initialized', async () => { const stateWithCache = new InMemoryState({}); - const cache = new StateCache(stateWithCache); + const cache = new StateCache(stateWithCache, mockLogger); const result = await cache.mdelete(['someKey', 'someOtherKey']); diff --git a/packages/tron-wallet-snap/src/caching/StateCache.ts b/packages/tron-wallet-snap/src/caching/StateCache.ts index 8f9ae7598..e1a07572a 100644 --- a/packages/tron-wallet-snap/src/caching/StateCache.ts +++ b/packages/tron-wallet-snap/src/caching/StateCache.ts @@ -1,7 +1,7 @@ +import type { Logger } from '@metamask/snap-networks-utils/logger'; import { assert } from '@metamask/utils'; import type { IStateManager } from '../services/state/IStateManager'; -import type { ILogger } from '../utils/logger'; import type { Serializable } from '../utils/serialization/types'; import type { ICache } from './ICache'; import type { CacheEntry } from './types'; @@ -74,11 +74,11 @@ export class StateCache implements ICache { public readonly prefix: CachePrefix; - public readonly logger: ILogger; + public readonly logger: Logger; constructor( state: IStateManager, - logger: ILogger = console, + logger: Logger, prefix: CachePrefix = '__cache__default', ) { this.#state = state; diff --git a/packages/tron-wallet-snap/src/clients/price-api/PriceApiClient.ts b/packages/tron-wallet-snap/src/clients/price-api/PriceApiClient.ts index 4f7a92d02..36dd344c2 100644 --- a/packages/tron-wallet-snap/src/clients/price-api/PriceApiClient.ts +++ b/packages/tron-wallet-snap/src/clients/price-api/PriceApiClient.ts @@ -1,6 +1,7 @@ /* eslint-disable @typescript-eslint/naming-convention */ import type { CaipAssetType } from '@metamask/keyring-api'; +import type { Logger } from '@metamask/snap-networks-utils/logger'; import { array, assert } from '@metamask/superstruct'; import { CaipAssetTypeStruct } from '@metamask/utils'; import { mapKeys } from 'lodash'; @@ -10,7 +11,6 @@ import { useCache } from '../../caching/useCache'; import { SNAP_OWNED_ASSETS } from '../../constants'; import type { ConfigProvider } from '../../services/config'; import { buildUrl } from '../../utils/buildUrl'; -import type { ILogger } from '../../utils/logger'; import logger from '../../utils/logger'; import type { Serializable } from '../../utils/serialization/types'; import { UrlStruct } from '../../validation/structs'; @@ -32,7 +32,7 @@ import { export class PriceApiClient { readonly #fetch: typeof globalThis.fetch; - readonly #logger: ILogger; + readonly #logger: Logger; readonly #baseUrl: string; @@ -50,7 +50,7 @@ export class PriceApiClient { configProvider: ConfigProvider, _cache: ICache, _fetch: typeof globalThis.fetch = globalThis.fetch, - _logger: ILogger = logger, + _logger: Logger = logger, ) { const { baseUrl, chunkSize, cacheTtlsMilliseconds } = configProvider.get().priceApi; diff --git a/packages/tron-wallet-snap/src/clients/security-alerts-api/SecurityAlertsApiClient.ts b/packages/tron-wallet-snap/src/clients/security-alerts-api/SecurityAlertsApiClient.ts index 65620a784..02972616d 100644 --- a/packages/tron-wallet-snap/src/clients/security-alerts-api/SecurityAlertsApiClient.ts +++ b/packages/tron-wallet-snap/src/clients/security-alerts-api/SecurityAlertsApiClient.ts @@ -1,11 +1,10 @@ /* eslint-disable @typescript-eslint/naming-convention */ +import type { Logger } from '@metamask/snap-networks-utils/logger'; import { assert } from '@metamask/superstruct'; import { Types as TronwebTypes } from 'tronweb'; import type { ConfigProvider } from '../../services/config'; -import { createPrefixedLogger } from '../../utils/logger'; -import type { ILogger } from '../../utils/logger'; import { isTransactionWellFormed } from '../../validation/transaction'; import { SecurityAlertResponseStruct } from './structs'; import type { SecurityAlertSimulationValidationResponse } from './structs'; @@ -51,7 +50,7 @@ export class SecurityAlertsApiClient { readonly #fetch: typeof globalThis.fetch; - readonly #logger: ILogger; + readonly #logger: Logger; readonly #baseUrl: string; @@ -61,9 +60,9 @@ export class SecurityAlertsApiClient { * @param configProvider - The configuration provider. * @param logger - Logger instance for logging. */ - constructor(configProvider: ConfigProvider, logger: ILogger) { + constructor(configProvider: ConfigProvider, logger: Logger) { this.#fetch = fetch; - this.#logger = createPrefixedLogger(logger, '[๐Ÿ”’ SecurityAlertsApiClient]'); + this.#logger = logger.withPrefix('[๐Ÿ”’ SecurityAlertsApiClient]'); this.#baseUrl = configProvider.get().securityAlertsApi.baseUrl; } diff --git a/packages/tron-wallet-snap/src/clients/snap/SnapClient.test.ts b/packages/tron-wallet-snap/src/clients/snap/SnapClient.test.ts index 686528183..0b16c87f5 100644 --- a/packages/tron-wallet-snap/src/clients/snap/SnapClient.test.ts +++ b/packages/tron-wallet-snap/src/clients/snap/SnapClient.test.ts @@ -1,4 +1,6 @@ -import type { ILogger } from '../../utils/logger'; +import type { Logger } from '@metamask/snap-networks-utils/logger'; + +import { mockLogger } from '../../utils/mockLogger'; import { SnapClient } from './SnapClient'; // Mock the global snap object @@ -18,17 +20,10 @@ async function withSnapClient( testFn: (setup: { snapClient: SnapClient; mockSnapRequest: jest.Mock; - mockLogger: jest.Mocked; + mockLogger: Logger; }) => void | Promise, ) { mockSnapRequest.mockReset(); - const mockLogger = { - log: jest.fn(), - info: jest.fn(), - warn: jest.fn(), - error: jest.fn(), - debug: jest.fn(), - } as unknown as jest.Mocked; const snapClient = new SnapClient({ logger: mockLogger }); await testFn({ snapClient, mockSnapRequest, mockLogger }); } @@ -124,7 +119,11 @@ describe('SnapClient', () => { describe('trackError', () => { it('returns the Sentry event ID and forwards the serialized error', async () => { await withSnapClient( - async ({ snapClient, mockSnapRequest: mockRequest, mockLogger }) => { + async ({ + snapClient, + mockSnapRequest: mockRequest, + mockLogger: logger, + }) => { mockRequest.mockResolvedValue('evt_abc123'); const error = new Error('boom'); error.name = 'BoomError'; @@ -143,22 +142,26 @@ describe('SnapClient', () => { }), }, }); - expect(mockLogger.warn).not.toHaveBeenCalled(); + expect(logger.warn).not.toHaveBeenCalled(); }, ); }); it('swallows RPC failures and logs a warning', async () => { await withSnapClient( - async ({ snapClient, mockSnapRequest: mockRequest, mockLogger }) => { + async ({ + snapClient, + mockSnapRequest: mockRequest, + mockLogger: logger, + }) => { const rpcError = new Error('rpc down'); mockRequest.mockRejectedValue(rpcError); const result = await snapClient.trackError(new Error('x')); expect(result).toBeUndefined(); - expect(mockLogger.warn).toHaveBeenCalledTimes(1); - expect(mockLogger.warn).toHaveBeenCalledWith( + expect(logger.warn).toHaveBeenCalledTimes(1); + expect(logger.warn).toHaveBeenCalledWith( expect.any(String), expect.objectContaining({ rpcError }), expect.stringContaining('Failed to track error'), diff --git a/packages/tron-wallet-snap/src/clients/snap/SnapClient.ts b/packages/tron-wallet-snap/src/clients/snap/SnapClient.ts index f2af912ec..79da8f053 100644 --- a/packages/tron-wallet-snap/src/clients/snap/SnapClient.ts +++ b/packages/tron-wallet-snap/src/clients/snap/SnapClient.ts @@ -1,5 +1,6 @@ import type { JsonSLIP10Node } from '@metamask/key-tree'; import type { EntropySourceId } from '@metamask/keyring-api'; +import type { Logger } from '@metamask/snap-networks-utils/logger'; import { getJsonError } from '@metamask/snaps-sdk'; import type { DialogResult, @@ -12,8 +13,6 @@ import type { import { SecurityEventType, TransactionEventType } from '../../types/analytics'; import type { Preferences } from '../../types/snap'; -import { createPrefixedLogger } from '../../utils/logger'; -import type { ILogger } from '../../utils/logger'; import { sanitizeSensitiveError } from '../../utils/sensitiveErrors'; /** @@ -21,10 +20,10 @@ import { sanitizeSensitiveError } from '../../utils/sensitiveErrors'; * Provides methods for managing interfaces, dialogs, preferences, and background events. */ export class SnapClient { - readonly #logger: ILogger; + readonly #logger: Logger; - constructor({ logger }: { logger: ILogger }) { - this.#logger = createPrefixedLogger(logger, '[๐Ÿ“ก SnapClient]'); + constructor({ logger }: { logger: Logger }) { + this.#logger = logger.withPrefix('[๐Ÿ“ก SnapClient]'); } /** diff --git a/packages/tron-wallet-snap/src/clients/token-api/TokenApiClient.ts b/packages/tron-wallet-snap/src/clients/token-api/TokenApiClient.ts index b40710fcc..f822ba4f3 100644 --- a/packages/tron-wallet-snap/src/clients/token-api/TokenApiClient.ts +++ b/packages/tron-wallet-snap/src/clients/token-api/TokenApiClient.ts @@ -1,3 +1,4 @@ +import type { Logger } from '@metamask/snap-networks-utils/logger'; import type { FungibleAssetMetadata } from '@metamask/snaps-sdk'; import { array, assert } from '@metamask/superstruct'; import type { Infer } from '@metamask/superstruct'; @@ -8,7 +9,6 @@ import type { TokenCaipAssetType } from '../../services/assets/types'; import { TokenCaipAssetTypeStruct } from '../../services/assets/types'; import type { ConfigProvider } from '../../services/config'; import { buildUrl } from '../../utils/buildUrl'; -import type { ILogger } from '../../utils/logger'; import logger from '../../utils/logger'; import { UrlStruct } from '../../validation/structs'; import { TokenMetadataResponseStruct } from './structs'; @@ -26,7 +26,7 @@ const DEFAULT_TOKEN_METADATA: FungibleAssetMetadata = { export class TokenApiClient { readonly #fetch: typeof globalThis.fetch; - readonly #logger: ILogger; + readonly #logger: Logger; readonly #baseUrl: string; @@ -43,7 +43,7 @@ export class TokenApiClient { constructor( configProvider: ConfigProvider, _fetch: typeof globalThis.fetch = globalThis.fetch, - _logger: ILogger = logger, + _logger: Logger = logger, ) { this.#fetch = _fetch; this.#logger = _logger; diff --git a/packages/tron-wallet-snap/src/context.ts b/packages/tron-wallet-snap/src/context.ts index 8a0484310..ad8ea8556 100644 --- a/packages/tron-wallet-snap/src/context.ts +++ b/packages/tron-wallet-snap/src/context.ts @@ -209,6 +209,7 @@ const confirmationHandler = new ConfirmationHandler({ tronWebFactory, assetsService, feeCalculatorService, + logger, }); /** diff --git a/packages/tron-wallet-snap/src/handlers/assets/assets.ts b/packages/tron-wallet-snap/src/handlers/assets/assets.ts index f7cc54289..f9dda22d0 100644 --- a/packages/tron-wallet-snap/src/handlers/assets/assets.ts +++ b/packages/tron-wallet-snap/src/handlers/assets/assets.ts @@ -1,3 +1,4 @@ +import type { Logger } from '@metamask/snap-networks-utils/logger'; import type { OnAssetHistoricalPriceArguments, OnAssetHistoricalPriceResponse, @@ -10,11 +11,9 @@ import type { } from '@metamask/snaps-sdk'; import type { AssetsService } from '../../services/assets/AssetsService'; -import type { ILogger } from '../../utils/logger'; -import { createPrefixedLogger } from '../../utils/logger'; export class AssetsHandler { - readonly #logger: ILogger; + readonly #logger: Logger; readonly #assetsService: AssetsService; @@ -22,10 +21,10 @@ export class AssetsHandler { logger, assetsService, }: { - logger: ILogger; + logger: Logger; assetsService: AssetsService; }) { - this.#logger = createPrefixedLogger(logger, '[๐Ÿช™ AssetsHandler]'); + this.#logger = logger.withPrefix('[๐Ÿช™ AssetsHandler]'); this.#assetsService = assetsService; } diff --git a/packages/tron-wallet-snap/src/handlers/clientRequest/clientRequest.ts b/packages/tron-wallet-snap/src/handlers/clientRequest/clientRequest.ts index 176c20b0b..46e0b2abb 100644 --- a/packages/tron-wallet-snap/src/handlers/clientRequest/clientRequest.ts +++ b/packages/tron-wallet-snap/src/handlers/clientRequest/clientRequest.ts @@ -1,4 +1,5 @@ import { TransactionStatus } from '@metamask/keyring-api'; +import type { Logger } from '@metamask/snap-networks-utils/logger'; import type { Json, JsonRpcRequest } from '@metamask/snaps-sdk'; import { InvalidParamsError, @@ -40,8 +41,6 @@ import { TransactionMapper } from '../../services/transactions/TransactionsMappe import type { TransactionsService } from '../../services/transactions/TransactionsService'; import { assertOrThrow } from '../../utils/assertOrThrow'; import { trxToSun } from '../../utils/conversion'; -import type { ILogger } from '../../utils/logger'; -import { createPrefixedLogger } from '../../utils/logger'; import { assertTransactionSignerConsistency, assertTransactionStructure, @@ -74,7 +73,7 @@ type TransactionRawData = TronwebTypes.Transaction['raw_data'] & { }; export class ClientRequestHandler { - readonly #logger: ILogger; + readonly #logger: Logger; readonly #accountsService: AccountsService; @@ -109,7 +108,7 @@ export class ClientRequestHandler { transactionsService, transactionExpirationRefresherService, }: { - logger: ILogger; + logger: Logger; accountsService: AccountsService; assetsService: AssetsService; sendService: SendService; @@ -121,7 +120,7 @@ export class ClientRequestHandler { transactionsService: TransactionsService; transactionExpirationRefresherService: TransactionExpirationRefresherService; }) { - this.#logger = createPrefixedLogger(logger, '[๐Ÿ‘‹ ClientRequestHandler]'); + this.#logger = logger.withPrefix('[๐Ÿ‘‹ ClientRequestHandler]'); this.#accountsService = accountsService; this.#assetsService = assetsService; this.#sendService = sendService; diff --git a/packages/tron-wallet-snap/src/handlers/cronjob/cronjob.test.tsx b/packages/tron-wallet-snap/src/handlers/cronjob/cronjob.test.tsx index fd4123d93..c6c02294a 100644 --- a/packages/tron-wallet-snap/src/handlers/cronjob/cronjob.test.tsx +++ b/packages/tron-wallet-snap/src/handlers/cronjob/cronjob.test.tsx @@ -18,7 +18,7 @@ import { FetchStatus } from '../../types/snap'; import { CONFIRM_SIGN_TRANSACTION_INTERFACE_NAME } from '../../ui/confirmation/views/ConfirmSignTransaction/types'; import type { ConfirmSignTransactionContext } from '../../ui/confirmation/views/ConfirmSignTransaction/types'; import type { ConfirmTransactionRequestContext } from '../../ui/confirmation/views/ConfirmTransactionRequest/types'; -import type { ILogger } from '../../utils/logger'; +import { mockLogger } from '../../utils/mockLogger'; import { BackgroundEventMethod, CronHandler } from './cronjob'; /** @@ -238,21 +238,6 @@ function buildMockSignTransactionInterfaceContext( }; } -/** - * Builds a mock logger satisfying the ILogger interface. - * - * @returns A mock ILogger. - */ -function buildMockLogger(): ILogger { - return { - log: jest.fn(), - info: jest.fn(), - warn: jest.fn(), - error: jest.fn(), - debug: jest.fn(), - }; -} - /** * Builds a mock SnapClient with only the methods exercised by the * `refreshConfirmationSend` flow. @@ -399,7 +384,7 @@ function buildCronHandler({ >; }): CronHandler { return new CronHandler({ - logger: buildMockLogger(), + logger: mockLogger, accountsService: {} as AccountsService, snapClient: mockSnapClient as unknown as SnapClient, state: mockState as unknown as State, @@ -961,7 +946,7 @@ describe('CronHandler', () => { getTransactionInfoById: jest.fn(), }; const cronHandler = new CronHandler({ - logger: buildMockLogger(), + logger: mockLogger, accountsService: mockAccountsService as unknown as AccountsService, snapClient: mockSnapClient as unknown as SnapClient, state: {} as unknown as State, diff --git a/packages/tron-wallet-snap/src/handlers/cronjob/cronjob.tsx b/packages/tron-wallet-snap/src/handlers/cronjob/cronjob.tsx index bcc30cbf4..90d0980ac 100644 --- a/packages/tron-wallet-snap/src/handlers/cronjob/cronjob.tsx +++ b/packages/tron-wallet-snap/src/handlers/cronjob/cronjob.tsx @@ -1,3 +1,4 @@ +import type { Logger } from '@metamask/snap-networks-utils/logger'; import type { JsonRpcRequest } from '@metamask/snaps-sdk'; import type { PriceApiClient } from '../../clients/price-api/PriceApiClient'; @@ -22,8 +23,6 @@ import type { ConfirmSignTransactionContext } from '../../ui/confirmation/views/ import { ConfirmTransactionRequest } from '../../ui/confirmation/views/ConfirmTransactionRequest/ConfirmTransactionRequest'; import { CONFIRM_TRANSACTION_INTERFACE_NAME } from '../../ui/confirmation/views/ConfirmTransactionRequest/types'; import type { ConfirmTransactionRequestContext } from '../../ui/confirmation/views/ConfirmTransactionRequest/types'; -import type { ILogger } from '../../utils/logger'; -import { createPrefixedLogger } from '../../utils/logger'; export enum CronjobMethod { ContinuouslySynchronizeSelectedAccounts = 'onSynchronizeSelectedAccountsCronjob', @@ -41,7 +40,7 @@ export enum BackgroundEventMethod { } export class CronHandler { - readonly #logger: ILogger; + readonly #logger: Logger; readonly #accountsService: AccountsService; @@ -67,7 +66,7 @@ export class CronHandler { transactionScanService, transactionExpirationRefresherService, }: { - logger: ILogger; + logger: Logger; accountsService: AccountsService; snapClient: SnapClient; state: State; @@ -76,7 +75,7 @@ export class CronHandler { transactionScanService: TransactionScanService; transactionExpirationRefresherService: TransactionExpirationRefresherService; }) { - this.#logger = createPrefixedLogger(logger, '[โฐ CronHandler]'); + this.#logger = logger.withPrefix('[โฐ CronHandler]'); this.#accountsService = accountsService; this.#snapClient = snapClient; this.#state = state; diff --git a/packages/tron-wallet-snap/src/handlers/keyring/keyring.ts b/packages/tron-wallet-snap/src/handlers/keyring/keyring.ts index 710278d18..d6f9398c9 100644 --- a/packages/tron-wallet-snap/src/handlers/keyring/keyring.ts +++ b/packages/tron-wallet-snap/src/handlers/keyring/keyring.ts @@ -18,6 +18,7 @@ import type { } from '@metamask/keyring-api/v2'; import { emitSnapKeyringEvent } from '@metamask/keyring-snap-sdk'; import { handleKeyringRequest } from '@metamask/keyring-snap-sdk/v2'; +import type { Logger } from '@metamask/snap-networks-utils/logger'; import { InvalidParamsError, SnapError, @@ -43,8 +44,6 @@ import type { ConfirmationHandler } from '../../services/confirmation/Confirmati import type { TransactionsService } from '../../services/transactions/TransactionsService'; import type { WalletService } from '../../services/wallet/WalletService'; import { sanitizeSensitiveError } from '../../utils/errors'; -import { createPrefixedLogger } from '../../utils/logger'; -import type { ILogger } from '../../utils/logger'; import { DeleteAccountStruct, ExportAccountRequestStruct, @@ -68,7 +67,7 @@ import { BackgroundEventMethod } from '../cronjob/cronjob'; import { TronMultichainMethod } from './keyring-types'; export class KeyringHandler implements KeyringSnapRpc { - readonly #logger: ILogger; + readonly #logger: Logger; readonly #snapClient: SnapClient; @@ -91,7 +90,7 @@ export class KeyringHandler implements KeyringSnapRpc { walletService, confirmationHandler, }: { - logger: ILogger; + logger: Logger; snapClient: SnapClient; accountsService: AccountsService; assetsService: AssetsService; @@ -99,7 +98,7 @@ export class KeyringHandler implements KeyringSnapRpc { walletService: WalletService; confirmationHandler: ConfirmationHandler; }) { - this.#logger = createPrefixedLogger(logger, '[๐Ÿ”‘ KeyringHandler]'); + this.#logger = logger.withPrefix('[๐Ÿ”‘ KeyringHandler]'); this.#snapClient = snapClient; this.#accountsService = accountsService; this.#assetsService = assetsService; diff --git a/packages/tron-wallet-snap/src/handlers/rpc/rpc.ts b/packages/tron-wallet-snap/src/handlers/rpc/rpc.ts index 7211653ca..a02c13a04 100644 --- a/packages/tron-wallet-snap/src/handlers/rpc/rpc.ts +++ b/packages/tron-wallet-snap/src/handlers/rpc/rpc.ts @@ -1,15 +1,14 @@ +import type { Logger } from '@metamask/snap-networks-utils/logger'; import { MethodNotFoundError } from '@metamask/snaps-sdk'; import type { Json, JsonRpcRequest } from '@metamask/snaps-sdk'; -import type { ILogger } from '../../utils/logger'; -import { createPrefixedLogger } from '../../utils/logger'; import { validateOrigin } from '../../validation/validators'; export class RpcHandler { - readonly #logger: ILogger; + readonly #logger: Logger; - constructor({ logger }: { logger: ILogger }) { - this.#logger = createPrefixedLogger(logger, '[๐Ÿ‘‹ RpcHandler]'); + constructor({ logger }: { logger: Logger }) { + this.#logger = logger.withPrefix('[๐Ÿ‘‹ RpcHandler]'); } async handle(origin: string, request: JsonRpcRequest): Promise { diff --git a/packages/tron-wallet-snap/src/handlers/user-input/userInput.ts b/packages/tron-wallet-snap/src/handlers/user-input/userInput.ts index a90ce4518..e064f1b90 100644 --- a/packages/tron-wallet-snap/src/handlers/user-input/userInput.ts +++ b/packages/tron-wallet-snap/src/handlers/user-input/userInput.ts @@ -1,14 +1,13 @@ +import type { Logger } from '@metamask/snap-networks-utils/logger'; import type { InterfaceContext, UserInputEvent } from '@metamask/snaps-sdk'; import type { SnapClient } from '../../clients/snap/SnapClient'; import { createEventHandlers as createSignMessageEvents } from '../../ui/confirmation/views/ConfirmSignMessage/events'; import { createEventHandlers as createSignTransactionEvents } from '../../ui/confirmation/views/ConfirmSignTransaction/events'; import { createEventHandlers as createTransactionConfirmationEvents } from '../../ui/confirmation/views/ConfirmTransactionRequest/events'; -import { createPrefixedLogger } from '../../utils/logger'; -import type { ILogger } from '../../utils/logger'; export class UserInputHandler { - readonly #logger: ILogger; + readonly #logger: Logger; readonly #snapClient: SnapClient; @@ -16,10 +15,10 @@ export class UserInputHandler { logger, snapClient, }: { - logger: ILogger; + logger: Logger; snapClient: SnapClient; }) { - this.#logger = createPrefixedLogger(logger, '[๐Ÿ‘ต LifecycleHandler]'); + this.#logger = logger.withPrefix('[๐Ÿ‘ต LifecycleHandler]'); this.#snapClient = snapClient; } diff --git a/packages/tron-wallet-snap/src/services/accounts/AccountsService.test.ts b/packages/tron-wallet-snap/src/services/accounts/AccountsService.test.ts index b75f006e0..7abaf08e2 100644 --- a/packages/tron-wallet-snap/src/services/accounts/AccountsService.test.ts +++ b/packages/tron-wallet-snap/src/services/accounts/AccountsService.test.ts @@ -17,12 +17,13 @@ import { emitSnapKeyringEvent, getSelectedAccounts, } from '@metamask/keyring-snap-sdk'; +import type { Logger } from '@metamask/snap-networks-utils/logger'; +import { LogLevel } from '@metamask/snap-networks-utils/logger'; import type { SnapClient } from '../../clients/snap/SnapClient'; import { Network } from '../../constants'; import type { NativeAsset } from '../../entities/assets'; import type { TronKeyringAccount } from '../../entities/keyring-account'; -import type { ILogger } from '../../utils/logger'; import { mockLogger } from '../../utils/mockLogger'; import type { AssetsService } from '../assets/AssetsService'; import type { ConfigProvider } from '../config'; @@ -62,6 +63,7 @@ const EMPTY_NETWORK_URLS: Record = { const MOCK_CONFIG: Config = { environment: 'test', + logLevel: LogLevel.INFO, networks: [], activeNetworks: [], priceApi: { @@ -117,7 +119,7 @@ type WithAccountsServiceCallback = (payload: { > >; mockConfigProvider: jest.Mocked>; - mockLogger: ILogger; + mockLogger: Logger; mockAssetsService: jest.Mocked< Pick >; diff --git a/packages/tron-wallet-snap/src/services/accounts/AccountsService.ts b/packages/tron-wallet-snap/src/services/accounts/AccountsService.ts index 3f2674fe8..88cca569e 100644 --- a/packages/tron-wallet-snap/src/services/accounts/AccountsService.ts +++ b/packages/tron-wallet-snap/src/services/accounts/AccountsService.ts @@ -14,6 +14,7 @@ import { emitSnapKeyringEvent, getSelectedAccounts, } from '@metamask/keyring-snap-sdk'; +import type { Logger } from '@metamask/snap-networks-utils/logger'; import type { Json } from '@metamask/snaps-sdk'; import { assert } from '@metamask/superstruct'; import { hexToBytes } from '@metamask/utils'; @@ -28,8 +29,6 @@ import type { TronKeyringAccount } from '../../entities/keyring-account'; import { createTronBip44AddressDeriver } from '../../utils/deriveTronFromCoinTypeNode'; import { sanitizeSensitiveError } from '../../utils/errors'; import { getLowestUnusedIndex } from '../../utils/getLowestUnusedIndex'; -import { createPrefixedLogger } from '../../utils/logger'; -import type { ILogger } from '../../utils/logger'; import { DerivationPathStruct } from '../../validation/structs'; import type { AssetsService } from '../assets/AssetsService'; import type { ConfigProvider } from '../config'; @@ -106,7 +105,7 @@ export class AccountsService { readonly #configProvider: ConfigProvider; - readonly #logger: ILogger; + readonly #logger: Logger; readonly #assetsService: AssetsService; @@ -124,12 +123,12 @@ export class AccountsService { }: { accountsRepository: AccountsRepository; configProvider: ConfigProvider; - logger: ILogger; + logger: Logger; assetsService: AssetsService; snapClient: SnapClient; transactionsService: TransactionsService; }) { - this.#logger = createPrefixedLogger(logger, '[๐Ÿ”‘ AccountsService]'); + this.#logger = logger.withPrefix('[๐Ÿ”‘ AccountsService]'); this.#configProvider = configProvider; this.#accountsRepository = accountsRepository; this.#assetsService = assetsService; diff --git a/packages/tron-wallet-snap/src/services/assets/adapters/CoreAssetsAdapter.ts b/packages/tron-wallet-snap/src/services/assets/adapters/CoreAssetsAdapter.ts index a71070cad..192187f25 100644 --- a/packages/tron-wallet-snap/src/services/assets/adapters/CoreAssetsAdapter.ts +++ b/packages/tron-wallet-snap/src/services/assets/adapters/CoreAssetsAdapter.ts @@ -7,14 +7,14 @@ import type { } from '@metamask/keyring-api'; import { emitSnapKeyringEvent } from '@metamask/keyring-snap-sdk'; import type { AssetsProvider } from '@metamask/snap-networks-utils'; +import { Logger } from '@metamask/snap-networks-utils/logger'; import type { TronHttpClient } from '../../../clients/tron-http/TronHttpClient'; import { TrongridAccountNotFoundError } from '../../../clients/trongrid/errors'; import type { TrongridApiClient } from '../../../clients/trongrid/TrongridApiClient'; import { Network } from '../../../constants'; import type { AssetEntity } from '../../../entities/assets'; -import type { ILogger } from '../../../utils/logger'; -import logger, { createPrefixedLogger } from '../../../utils/logger'; +import logger from '../../../utils/logger'; import { buildStakedData } from '../utils/buildStakedData'; import { extractBandwidth } from '../utils/extractBandwidth'; import { extractEnergy } from '../utils/extractEnergy'; @@ -39,7 +39,7 @@ export type CoreAssetsAdapterOptions = { * published via keyring events without local persistence when migration is active. */ export class CoreAssetsAdapter { - readonly #logger: ILogger; + readonly #logger: Logger; readonly #getAccountAssetByID: AssetsProvider['getAccountAssetByID']; @@ -63,7 +63,7 @@ export class CoreAssetsAdapter { getAddressStakingRewards, } = options; - this.#logger = createPrefixedLogger(logger, '[CoreAssetsAdapter]'); + this.#logger = logger.withPrefix('[CoreAssetsAdapter]'); this.#getAccountAssetByID = getAccountAssetByID; this.#getAccountAssetsByIDs = getAccountAssetsByIDs; this.#getAccountAssetsByScope = getAccountAssetsByScope; diff --git a/packages/tron-wallet-snap/src/services/assets/adapters/SnapAssetsAdapter.ts b/packages/tron-wallet-snap/src/services/assets/adapters/SnapAssetsAdapter.ts index 7a5b38d3b..215239d43 100644 --- a/packages/tron-wallet-snap/src/services/assets/adapters/SnapAssetsAdapter.ts +++ b/packages/tron-wallet-snap/src/services/assets/adapters/SnapAssetsAdapter.ts @@ -5,6 +5,7 @@ import type { KeyringAccount, } from '@metamask/keyring-api'; import { emitSnapKeyringEvent } from '@metamask/keyring-snap-sdk'; +import type { Logger } from '@metamask/snap-networks-utils/logger'; import type { AssetConversion, AssetMetadata, @@ -55,8 +56,6 @@ import { } from '../../../constants'; import type { AssetEntity } from '../../../entities/assets'; import { toUiAmount } from '../../../utils/conversion'; -import { createPrefixedLogger } from '../../../utils/logger'; -import type { ILogger } from '../../../utils/logger'; import type { ConfigProvider } from '../../config'; import type { State, UnencryptedStateValue } from '../../state/State'; import type { AssetsRepository } from '../AssetsRepository'; @@ -101,7 +100,7 @@ type NormalizedAccountData = { }; export class SnapAssetsAdapter { - readonly #logger: ILogger; + readonly #logger: Logger; readonly #assetsRepository: AssetsRepository; @@ -136,7 +135,7 @@ export class SnapAssetsAdapter { snapClient, configProvider, }: { - logger: ILogger; + logger: Logger; assetsRepository: AssetsRepository; state: State; trongridApiClient: TrongridApiClient; @@ -146,7 +145,7 @@ export class SnapAssetsAdapter { snapClient: SnapClient; configProvider: ConfigProvider; }) { - this.#logger = createPrefixedLogger(logger, '[๐Ÿช™ SnapAssetsAdapter]'); + this.#logger = logger.withPrefix('[๐Ÿช™ SnapAssetsAdapter]'); this.#assetsRepository = assetsRepository; this.#state = state; this.#trongridApiClient = trongridApiClient; diff --git a/packages/tron-wallet-snap/src/services/config/ConfigProvider.ts b/packages/tron-wallet-snap/src/services/config/ConfigProvider.ts index 33c6d6bf6..2c9dbc49a 100644 --- a/packages/tron-wallet-snap/src/services/config/ConfigProvider.ts +++ b/packages/tron-wallet-snap/src/services/config/ConfigProvider.ts @@ -1,3 +1,4 @@ +import { LogLevel } from '@metamask/snap-networks-utils/logger'; /* eslint-disable no-restricted-globals */ import type { Infer } from '@metamask/superstruct'; import { @@ -27,6 +28,7 @@ const CommaSeparatedListOfUrlsStruct = coerce( const EnvStruct = object({ ENVIRONMENT: enums(['local', 'test', 'production']), + LOG_LEVEL: enums(Object.values(LogLevel)), RPC_URL_LIST_MAINNET: CommaSeparatedListOfUrlsStruct, RPC_URL_LIST_NILE_TESTNET: CommaSeparatedListOfUrlsStruct, RPC_URL_LIST_SHASTA_TESTNET: CommaSeparatedListOfUrlsStruct, @@ -56,6 +58,7 @@ export type NetworkConfig = (typeof Networks)[Network] & { export type Config = { environment: string; + logLevel: LogLevel; networks: NetworkConfig[]; activeNetworks: Network[]; priceApi: { @@ -116,6 +119,7 @@ export class ConfigProvider { #parseEnvironment(): Env { const rawEnvironment = { ENVIRONMENT: process.env.ENVIRONMENT, + LOG_LEVEL: process.env.LOG_LEVEL, // RPC RPC_URL_LIST_MAINNET: process.env.RPC_URL_LIST_MAINNET, RPC_URL_LIST_NILE_TESTNET: process.env.RPC_URL_LIST_NILE_TESTNET, @@ -148,6 +152,7 @@ export class ConfigProvider { #buildConfig(environment: Env): Config { return { environment: environment.ENVIRONMENT, + logLevel: environment.LOG_LEVEL, networks: [ { ...Networks[Network.Mainnet], diff --git a/packages/tron-wallet-snap/src/services/confirmation/ConfirmationHandler.test.ts b/packages/tron-wallet-snap/src/services/confirmation/ConfirmationHandler.test.ts index 6df1bffac..a93fbaffb 100644 --- a/packages/tron-wallet-snap/src/services/confirmation/ConfirmationHandler.test.ts +++ b/packages/tron-wallet-snap/src/services/confirmation/ConfirmationHandler.test.ts @@ -10,6 +10,7 @@ import { TronMultichainMethod } from '../../handlers/keyring/keyring-types'; import { getIconUrlForKnownAsset } from '../../ui/confirmation/utils/getIconUrlForKnownAsset'; import { render as renderConfirmSignTransaction } from '../../ui/confirmation/views/ConfirmSignTransaction/render'; import { render as renderConfirmTransactionRequest } from '../../ui/confirmation/views/ConfirmTransactionRequest/render'; +import { mockLogger } from '../../utils/mockLogger'; import type { AssetsService } from '../assets/AssetsService'; import type { FeeCalculatorService } from '../send/FeeCalculatorService'; import type { ComputeFeeResult } from '../send/types'; @@ -197,6 +198,7 @@ async function withConfirmationHandler( tronWebFactory: mockTronWebFactory, assetsService: mockAssetsService, feeCalculatorService: mockFeeCalculatorService, + logger: mockLogger, }); return await testFunction({ diff --git a/packages/tron-wallet-snap/src/services/confirmation/ConfirmationHandler.ts b/packages/tron-wallet-snap/src/services/confirmation/ConfirmationHandler.ts index f48364eb1..99432ece0 100644 --- a/packages/tron-wallet-snap/src/services/confirmation/ConfirmationHandler.ts +++ b/packages/tron-wallet-snap/src/services/confirmation/ConfirmationHandler.ts @@ -1,3 +1,4 @@ +import type { Logger } from '@metamask/snap-networks-utils/logger'; import { InternalError } from '@metamask/snaps-sdk'; import { assert } from '@metamask/superstruct'; import { BigNumber } from 'bignumber.js'; @@ -21,8 +22,6 @@ import type { ConfirmSignTransactionContext } from '../../ui/confirmation/views/ import { render as renderConfirmTransactionRequest } from '../../ui/confirmation/views/ConfirmTransactionRequest/render'; import { CONFIRM_TRANSACTION_INTERFACE_NAME } from '../../ui/confirmation/views/ConfirmTransactionRequest/types'; import { formatOrigin } from '../../utils/formatOrigin'; -import type { ILogger } from '../../utils/logger'; -import logger, { createPrefixedLogger } from '../../utils/logger'; import { SignTransactionRequestStruct } from '../../validation/structs'; import type { TronWalletKeyringRequest } from '../../validation/structs'; import { assertTransactionStructure } from '../../validation/transaction'; @@ -32,7 +31,7 @@ import type { ComputeFeeResult } from '../send/types'; import type { State, UnencryptedStateValue } from '../state/State'; export class ConfirmationHandler { - readonly #logger: ILogger; + readonly #logger: Logger; readonly #snapClient: SnapClient; @@ -50,14 +49,16 @@ export class ConfirmationHandler { tronWebFactory, assetsService, feeCalculatorService, + logger, }: { snapClient: SnapClient; state: State; tronWebFactory: TronWebFactory; assetsService: AssetsService; feeCalculatorService: FeeCalculatorService; + logger: Logger; }) { - this.#logger = createPrefixedLogger(logger, '[๐Ÿ”‘ ConfirmationHandler]'); + this.#logger = logger.withPrefix('[๐Ÿ”‘ ConfirmationHandler]'); this.#snapClient = snapClient; this.#state = state; this.#tronWebFactory = tronWebFactory; diff --git a/packages/tron-wallet-snap/src/services/send/FeeCalculatorService.ts b/packages/tron-wallet-snap/src/services/send/FeeCalculatorService.ts index 245e34732..185bbce77 100644 --- a/packages/tron-wallet-snap/src/services/send/FeeCalculatorService.ts +++ b/packages/tron-wallet-snap/src/services/send/FeeCalculatorService.ts @@ -1,5 +1,6 @@ /* eslint-disable @typescript-eslint/naming-convention */ import { FeeType } from '@metamask/keyring-api'; +import type { Logger } from '@metamask/snap-networks-utils/logger'; import { BigNumber } from 'bignumber.js'; import type { Types as TronwebTypes } from 'tronweb'; @@ -23,8 +24,6 @@ import { SUN_IN_TRX, ZERO, } from '../../constants'; -import type { ILogger } from '../../utils/logger'; -import { createPrefixedLogger } from '../../utils/logger'; import { FeeUnavailableError } from './errors'; import type { ComputeFeeResult } from './types'; @@ -128,7 +127,7 @@ const ZERO_ENERGY_SYSTEM_CONTRACTS = new Set([ ]); export class FeeCalculatorService { - readonly #logger: ILogger; + readonly #logger: Logger; readonly #trongridApiClient: TrongridApiClient; @@ -142,12 +141,12 @@ export class FeeCalculatorService { tronHttpClient, snapClient, }: { - logger: ILogger; + logger: Logger; trongridApiClient: TrongridApiClient; tronHttpClient: TronHttpClient; snapClient: SnapClient; }) { - this.#logger = createPrefixedLogger(logger, '[๐Ÿ’ธ FeeCalculatorService]'); + this.#logger = logger.withPrefix('[๐Ÿ’ธ FeeCalculatorService]'); this.#trongridApiClient = trongridApiClient; this.#tronHttpClient = tronHttpClient; this.#snapClient = snapClient; diff --git a/packages/tron-wallet-snap/src/services/send/SendService.ts b/packages/tron-wallet-snap/src/services/send/SendService.ts index 6e8f2b233..637e9f20c 100644 --- a/packages/tron-wallet-snap/src/services/send/SendService.ts +++ b/packages/tron-wallet-snap/src/services/send/SendService.ts @@ -1,3 +1,4 @@ +import type { Logger } from '@metamask/snap-networks-utils/logger'; import { parseCaipAssetType } from '@metamask/utils'; import { BigNumber } from 'bignumber.js'; import type { TronWeb, Types as TronwebTypes } from 'tronweb'; @@ -10,8 +11,6 @@ import type { AssetEntity } from '../../entities/assets'; import { SendErrorCodes } from '../../handlers/clientRequest/types'; import { BackgroundEventMethod } from '../../handlers/cronjob/cronjob'; import { toRawAmount, trxToSun } from '../../utils/conversion'; -import { createPrefixedLogger } from '../../utils/logger'; -import type { ILogger } from '../../utils/logger'; import { assertTransactionSignerConsistency } from '../../validation/transaction'; import type { AccountsService } from '../accounts/AccountsService'; import type { AssetsService } from '../assets/AssetsService'; @@ -28,7 +27,7 @@ export class SendService { readonly #feeCalculatorService: FeeCalculatorService; - readonly #logger: ILogger; + readonly #logger: Logger; readonly #snapClient: SnapClient; @@ -47,7 +46,7 @@ export class SendService { assetsService: AssetsService; tronWebFactory: TronWebFactory; feeCalculatorService: FeeCalculatorService; - logger: ILogger; + logger: Logger; snapClient: SnapClient; transactionExpirationRefresherService: TransactionExpirationRefresherService; }) { @@ -55,7 +54,7 @@ export class SendService { this.#assetsService = assetsService; this.#tronWebFactory = tronWebFactory; this.#feeCalculatorService = feeCalculatorService; - this.#logger = createPrefixedLogger(logger, '[๐Ÿ’ธ SendService]'); + this.#logger = logger.withPrefix('[๐Ÿ’ธ SendService]'); this.#snapClient = snapClient; this.#transactionExpirationRefresherService = transactionExpirationRefresherService; diff --git a/packages/tron-wallet-snap/src/services/staking/StakingService.ts b/packages/tron-wallet-snap/src/services/staking/StakingService.ts index c158520d6..86f8961b2 100644 --- a/packages/tron-wallet-snap/src/services/staking/StakingService.ts +++ b/packages/tron-wallet-snap/src/services/staking/StakingService.ts @@ -1,3 +1,4 @@ +import type { Logger } from '@metamask/snap-networks-utils/logger'; import { parseCaipAssetType } from '@metamask/utils'; import { BigNumber } from 'bignumber.js'; import type { Types as TronwebTypes } from 'tronweb'; @@ -9,13 +10,11 @@ import { CONSENSYS_SR_NODE_ADDRESS, KnownCaip19Id } from '../../constants'; import type { TronKeyringAccount } from '../../entities/keyring-account'; import { trxToSun } from '../../utils/conversion'; import { executeOnChainActions } from '../../utils/executeOnChainActions'; -import type { ILogger } from '../../utils/logger'; -import { createPrefixedLogger } from '../../utils/logger'; import type { AccountsService } from '../accounts/AccountsService'; import type { NativeCaipAssetType, StakedCaipAssetType } from '../assets/types'; export class StakingService { - readonly #logger: ILogger; + readonly #logger: Logger; readonly #accountsService: AccountsService; @@ -29,12 +28,12 @@ export class StakingService { tronWebFactory, snapClient, }: { - logger: ILogger; + logger: Logger; accountsService: AccountsService; tronWebFactory: TronWebFactory; snapClient: SnapClient; }) { - this.#logger = createPrefixedLogger(logger, '[๐Ÿ’ธ StakingService]'); + this.#logger = logger.withPrefix('[๐Ÿ’ธ StakingService]'); this.#accountsService = accountsService; this.#tronWebFactory = tronWebFactory; this.#snapClient = snapClient; diff --git a/packages/tron-wallet-snap/src/services/transaction-scan/TransactionScanService.ts b/packages/tron-wallet-snap/src/services/transaction-scan/TransactionScanService.ts index 3921fcef5..f3b5f2d36 100644 --- a/packages/tron-wallet-snap/src/services/transaction-scan/TransactionScanService.ts +++ b/packages/tron-wallet-snap/src/services/transaction-scan/TransactionScanService.ts @@ -1,3 +1,4 @@ +import type { Logger } from '@metamask/snap-networks-utils/logger'; import { BigNumber } from 'bignumber.js'; import type { Types as TronwebTypes } from 'tronweb'; @@ -10,7 +11,6 @@ import type { import type { SnapClient } from '../../clients/snap/SnapClient'; import type { Network } from '../../constants'; import type { TronKeyringAccount } from '../../entities/keyring-account'; -import type { ILogger } from '../../utils/logger'; import { isTransactionWellFormed } from '../../validation/transaction'; import type { TransactionScanAssetChange, @@ -28,12 +28,12 @@ export class TransactionScanService { readonly #snapClient: SnapClient; - readonly #logger: ILogger; + readonly #logger: Logger; constructor( securityAlertsApiClient: SecurityAlertsApiClient, snapClient: SnapClient, - logger: ILogger, + logger: Logger, ) { this.#securityAlertsApiClient = securityAlertsApiClient; this.#snapClient = snapClient; diff --git a/packages/tron-wallet-snap/src/services/transactions/TransactionsService.test.ts b/packages/tron-wallet-snap/src/services/transactions/TransactionsService.test.ts index 02563a10a..36a1e06cc 100644 --- a/packages/tron-wallet-snap/src/services/transactions/TransactionsService.test.ts +++ b/packages/tron-wallet-snap/src/services/transactions/TransactionsService.test.ts @@ -1,6 +1,7 @@ /* eslint-disable @typescript-eslint/no-non-null-assertion */ import type { Transaction } from '@metamask/keyring-api'; import { TransactionStatus, TransactionType } from '@metamask/keyring-api'; +import type { Logger } from '@metamask/snap-networks-utils/logger'; import type { PriceApiClient } from '../../clients/price-api/PriceApiClient'; import type { SnapClient } from '../../clients/snap/SnapClient'; @@ -12,7 +13,6 @@ import type { } from '../../clients/trongrid/types'; import { KnownCaip19Id, Network, Networks } from '../../constants'; import type { TronKeyringAccount } from '../../entities/keyring-account'; -import type { ILogger } from '../../utils/logger'; import { mockLogger } from '../../utils/mockLogger'; import nativeTransferMock from './mocks/trongrid/account-transactions/native-transfer.json'; import trc10TransferMock from './mocks/trongrid/account-transactions/trc10-transfer.json'; @@ -24,7 +24,7 @@ import { TransactionsService } from './TransactionsService'; type WithTransactionServiceCallback = (payload: { transactionsService: TransactionsService; - mockLogger: ILogger; + mockLogger: Logger; mockTransactionsRepository: jest.Mocked< Pick< TransactionsRepository, diff --git a/packages/tron-wallet-snap/src/services/transactions/TransactionsService.ts b/packages/tron-wallet-snap/src/services/transactions/TransactionsService.ts index 09f87833b..789822ffe 100644 --- a/packages/tron-wallet-snap/src/services/transactions/TransactionsService.ts +++ b/packages/tron-wallet-snap/src/services/transactions/TransactionsService.ts @@ -1,6 +1,7 @@ import type { CaipAssetType, Transaction } from '@metamask/keyring-api'; import { KeyringEvent, TransactionType } from '@metamask/keyring-api'; import { emitSnapKeyringEvent } from '@metamask/keyring-snap-sdk'; +import type { Logger } from '@metamask/snap-networks-utils/logger'; import { groupBy } from 'lodash'; import type { PriceApiClient } from '../../clients/price-api/PriceApiClient'; @@ -16,14 +17,12 @@ import type { } from '../../clients/trongrid/types'; import type { Network } from '../../constants'; import type { TronKeyringAccount } from '../../entities/keyring-account'; -import type { ILogger } from '../../utils/logger'; -import { createPrefixedLogger } from '../../utils/logger'; import { TransactionMapper } from './TransactionsMapper'; import type { TransactionsRepository } from './TransactionsRepository'; import { isSpam } from './utils/isSpam'; export class TransactionsService { - readonly #logger: ILogger; + readonly #logger: Logger; readonly #transactionsRepository: TransactionsRepository; @@ -43,14 +42,14 @@ export class TransactionsService { priceApiClient, snapClient, }: { - logger: ILogger; + logger: Logger; transactionsRepository: TransactionsRepository; trongridApiClient: TrongridApiClient; tronHttpClient: TronHttpClient; priceApiClient: PriceApiClient; snapClient: SnapClient; }) { - this.#logger = createPrefixedLogger(logger, '[๐Ÿงพ TransactionsService]'); + this.#logger = logger.withPrefix('[๐Ÿงพ TransactionsService]'); this.#transactionsRepository = transactionsRepository; this.#trongridApiClient = trongridApiClient; this.#tronHttpClient = tronHttpClient; diff --git a/packages/tron-wallet-snap/src/services/wallet/WalletService.ts b/packages/tron-wallet-snap/src/services/wallet/WalletService.ts index ebfbbefbd..a92976446 100644 --- a/packages/tron-wallet-snap/src/services/wallet/WalletService.ts +++ b/packages/tron-wallet-snap/src/services/wallet/WalletService.ts @@ -1,4 +1,5 @@ import type { ResolvedAccountAddress } from '@metamask/keyring-api'; +import type { Logger } from '@metamask/snap-networks-utils/logger'; import { SnapError } from '@metamask/snaps-sdk'; import type { Json, JsonRpcRequest } from '@metamask/snaps-sdk'; import { bytesToHex, hexToBytes, sha256 } from '@metamask/utils'; @@ -10,8 +11,6 @@ import { TronMultichainErrors, TronMultichainMethod, } from '../../handlers/keyring/keyring-types'; -import { createPrefixedLogger } from '../../utils/logger'; -import type { ILogger } from '../../utils/logger'; import { ResolveAccountAddressRequestStruct, ResolveAccountAddressResponseStruct, @@ -29,7 +28,7 @@ import type { AccountsService } from '../accounts/AccountsService'; * Service responsible for handling wallet operations like signing messages and transactions. */ export class WalletService { - readonly #logger: ILogger; + readonly #logger: Logger; readonly #accountsService: AccountsService; @@ -40,11 +39,11 @@ export class WalletService { accountsService, tronWebFactory, }: { - logger: ILogger; + logger: Logger; accountsService: AccountsService; tronWebFactory: TronWebFactory; }) { - this.#logger = createPrefixedLogger(logger, '[๐Ÿ’ผ WalletService]'); + this.#logger = logger.withPrefix('[๐Ÿ’ผ WalletService]'); this.#accountsService = accountsService; this.#tronWebFactory = tronWebFactory; } diff --git a/packages/tron-wallet-snap/src/utils/errors.test.ts b/packages/tron-wallet-snap/src/utils/errors.test.ts index 6d142f73d..ea9d33ffe 100644 --- a/packages/tron-wallet-snap/src/utils/errors.test.ts +++ b/packages/tron-wallet-snap/src/utils/errors.test.ts @@ -1,7 +1,7 @@ import { SnapError, UserRejectedRequestError } from '@metamask/snaps-sdk'; import { shouldTrackError, withCatchAndThrowSnapError } from './errors'; -import logger from './logger'; +import { mockLogger } from './mockLogger'; jest.mock('../clients/snap/SnapClient', () => { const trackError = jest.fn(); @@ -14,16 +14,14 @@ jest.mock('../clients/snap/SnapClient', () => { }; }); -// Mock the logger to avoid actual console output during tests jest.mock('./logger', () => ({ - error: jest.fn(), + __esModule: true, + default: jest.requireActual('./mockLogger').mockLogger, })); const { trackError } = jest.requireMock('../clients/snap/SnapClient'); describe('errors', () => { - const mockLogger = logger as jest.Mocked; - beforeEach(() => { jest.clearAllMocks(); }); @@ -95,7 +93,8 @@ describe('errors', () => { expect(mockLogger.error).toHaveBeenCalledTimes(1); const logCall = mockLogger.error.mock.calls[0]; - const loggedError = logCall?.[0]?.error; + const loggedError = (logCall?.[0] as { error?: unknown } | undefined) + ?.error; expect(loggedError).toBeInstanceOf(SnapError); }); @@ -109,7 +108,8 @@ describe('errors', () => { expect(mockLogger.error).toHaveBeenCalledTimes(1); const logCall = mockLogger.error.mock.calls[0]; - const loggedError = logCall?.[0]?.error; + const loggedError = (logCall?.[0] as { error?: unknown } | undefined) + ?.error; expect(loggedError).toBeInstanceOf(SnapError); }); @@ -180,9 +180,12 @@ describe('errors', () => { for (let i = 0; i < errorTypes.length; i++) { const logCall = logCalls[i]; - const loggedError = logCall?.[0]?.error; + const loggedError = (logCall?.[0] as { error?: unknown } | undefined) + ?.error; expect(loggedError).toBeInstanceOf(SnapError); - expect(loggedError?.message).toBe(errorTypes[i]?.message); + expect((loggedError as Error | undefined)?.message).toBe( + errorTypes[i]?.message, + ); } }); diff --git a/packages/tron-wallet-snap/src/utils/logger.ts b/packages/tron-wallet-snap/src/utils/logger.ts index 4a093c287..ebf4fb9e0 100644 --- a/packages/tron-wallet-snap/src/utils/logger.ts +++ b/packages/tron-wallet-snap/src/utils/logger.ts @@ -1,99 +1,11 @@ -/* eslint-disable no-empty-function */ +import { Logger, LogLevel } from '@metamask/snap-networks-utils/logger'; -/** - * A simple logger utility that provides methods for logging messages at different levels. - * For now, it's just a wrapper around console. - * - * @namespace logger - */ +import { ConfigProvider } from '../services/config'; -export type ILogger = { - // TODO: Replace `any` with type - // eslint-disable-next-line @typescript-eslint/no-explicit-any - log: (...args: any[]) => void; - // TODO: Replace `any` with type - // eslint-disable-next-line @typescript-eslint/no-explicit-any - info: (...args: any[]) => void; - // TODO: Replace `any` with type - // eslint-disable-next-line @typescript-eslint/no-explicit-any - warn: (...args: any[]) => void; - // TODO: Replace `any` with type - // eslint-disable-next-line @typescript-eslint/no-explicit-any - error: (...args: any[]) => void; - // TODO: Replace `any` with type - // eslint-disable-next-line @typescript-eslint/no-explicit-any - debug: (...args: any[]) => void; -}; +export const configProvider = new ConfigProvider(); -const withErrorLogging = - // TODO: Replace `any` with type - // eslint-disable-next-line @typescript-eslint/no-explicit-any - (logFn: (...args: any[]) => void) => - // TODO: Replace `any` with type - // eslint-disable-next-line @typescript-eslint/no-explicit-any - (...args: any[]): void => { - logFn(...args); - }; +const logger = new Logger({ level: configProvider.get().logLevel }); -/** - * A decorator function that noops if the environment is not local, - * and runs the decorated function otherwise. - * - * @param fn - The function to wrap. - * @returns The wrapped function. - */ -const withNoopInProduction = - // TODO: Replace `any` with type - // eslint-disable-next-line @typescript-eslint/no-explicit-any - (fn: (...args: any[]) => void) => - // TODO: Replace `any` with type - // eslint-disable-next-line @typescript-eslint/no-explicit-any - (...args: any[]): void => { - // eslint-disable-next-line no-restricted-globals - if (process.env.ENVIRONMENT === 'production') { - return; - } - fn(...args); - }; - -/** - * A basic logger that wraps the console, extending its functionality to properly log Tron errors. - */ -const logger: ILogger = { - log: withNoopInProduction(console.log), - info: withNoopInProduction(console.info), - warn: withNoopInProduction(console.warn), - debug: withNoopInProduction(console.debug), - error: withNoopInProduction(withErrorLogging(console.error)), -}; - -export const noOpLogger: ILogger = { - log: () => {}, - info: () => {}, - warn: () => {}, - debug: () => {}, - error: () => {}, -}; - -export const createPrefixedLogger = ( - _logger: ILogger, - prefix: string, -): ILogger => { - return new Proxy(_logger, { - // TODO: Replace `any` with type - // eslint-disable-next-line @typescript-eslint/no-explicit-any - get(target, prop: keyof ILogger): any { - const method = target[prop]; - if (typeof method === 'function') { - // TODO: Replace `any` with type - // eslint-disable-next-line @typescript-eslint/no-explicit-any - return (message: string, ...args: any[]) => { - return method.call(target, prefix, message, ...args); - }; - } - return method; - }, - }); -}; +export const noOpLogger = new Logger({ level: LogLevel.SILENT }); export default logger; diff --git a/packages/tron-wallet-snap/src/utils/mockLogger.ts b/packages/tron-wallet-snap/src/utils/mockLogger.ts index 17c513cff..aa2a641a1 100644 --- a/packages/tron-wallet-snap/src/utils/mockLogger.ts +++ b/packages/tron-wallet-snap/src/utils/mockLogger.ts @@ -1,4 +1,4 @@ -import type { ILogger } from './logger'; +import type { Logger } from '@metamask/snap-networks-utils/logger'; export const mockLogger = { log: jest.fn(), @@ -6,4 +6,21 @@ export const mockLogger = { warn: jest.fn(), error: jest.fn(), debug: jest.fn(), -} as unknown as ILogger; + trace: jest.fn(), + withPrefix: (prefix: string): Logger => createPrefixedLogger([prefix]), +} as unknown as jest.Mocked; + +function createPrefixedLogger(prefixes: string[]): Logger { + return new Proxy(mockLogger, { + get(target, property: keyof Logger): unknown { + if (property === 'withPrefix') { + return (prefix: string) => createPrefixedLogger([...prefixes, prefix]); + } + + const method = target[property]; + return typeof method === 'function' + ? (...args: unknown[]): unknown => method(...prefixes, ...args) + : method; + }, + }); +}