Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
31 commits
Select commit Hold shift + click to select a range
da93dcc
feat: integrate error tracking service with RPC handlers
mj-kiwi Jan 6, 2026
492d4ab
Merge branch 'main' into feat/error-tracking
mj-kiwi Jan 15, 2026
c5f08dc
fix: correct indentation for i18n initialization in onRpcRequest handler
mj-kiwi Jan 15, 2026
a3f3f56
Merge branch 'main' into feat/error-tracking
mj-kiwi Jan 15, 2026
244595a
feat: integrate error tracking functionality across RPC handlers
mj-kiwi Jan 15, 2026
e97b037
refactor: remove rpcErrorHandler files and clean up package.json exports
mj-kiwi Jan 19, 2026
a3a5fcf
feat: add unit tests for SnapErrorTracker functionality and behavior
mj-kiwi Jan 20, 2026
797c47a
Merge branch 'main' into feat/error-tracking
mj-kiwi Jan 20, 2026
876aa4a
fix: update import statement for ErrorTrackingConfig to use type import
mj-kiwi Jan 20, 2026
0941e99
refactor: update shouldTrackError to use explicit boolean return type…
mj-kiwi Jan 20, 2026
c997296
refactor: enhance error handling in SnapErrorTracker and simplify ins…
mj-kiwi Jan 20, 2026
d4d7517
Merge branch 'main' into feat/error-tracking
mj-kiwi Jan 25, 2026
632e27a
Merge branch 'main' into feat/error-tracking
mj-kiwi Jan 27, 2026
b299440
feat: enhance error tracking by including request parameters in error…
mj-kiwi Jan 27, 2026
a7a9ba7
test: enhance error tracking tests to handle empty error messages
mj-kiwi Jan 28, 2026
1d5c498
Merge branch 'main' into feat/error-tracking
mj-kiwi Jan 28, 2026
8a145a4
Merge branch 'main' into feat/error-tracking
mj-kiwi Jan 28, 2026
3be17e2
fix: improve error tracking logic to handle null and undefined error …
mj-kiwi Jan 28, 2026
372f177
refactor: remove setEnabled and isEnabled methods from SnapErrorTrack…
mj-kiwi Jan 28, 2026
ae6d406
refactor: change #enabled property to readonly in SnapErrorTracker class
mj-kiwi Jan 28, 2026
633037f
fix: reorder processing lock checks in onRpcRequest to improve error …
mj-kiwi Jan 28, 2026
f6e6868
refactor: update error tracking implementation to use snapProvider an…
mj-kiwi Jan 29, 2026
cd4d408
refactor: update error capturing to use structured error objects and …
mj-kiwi Jan 29, 2026
358da1c
test: add case to track string errors with default filter in SnapErro…
mj-kiwi Jan 29, 2026
776130c
refactor: use optional chaining for request properties in error tracking
mj-kiwi Jan 29, 2026
515144a
refactor: replace console.warn with logger.warn for error tracking
mj-kiwi Jan 29, 2026
626edba
refactor: streamline logger warning spy implementation in error track…
mj-kiwi Jan 29, 2026
642ea4f
refactor: update comment to clarify lock token creation in onRpcReque…
mj-kiwi Jan 29, 2026
9fde26f
refactor: enhance error handling to preserve falsy message values for…
mj-kiwi Jan 29, 2026
98f9432
refactor: improve error tracking by releasing lock without awaiting c…
mj-kiwi Jan 29, 2026
e6cc6b0
refactor: enhance error tracking by allowing captureError to handle p…
mj-kiwi Jan 29, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
65 changes: 46 additions & 19 deletions packages/gator-permissions-snap/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
/* eslint-disable no-restricted-globals */
import { logger } from '@metamask/7715-permissions-shared/utils';
import {
logger,
createErrorTracker,
} from '@metamask/7715-permissions-shared/utils';
import {
AuthType,
JwtBearerAuth,
Expand Down Expand Up @@ -195,6 +198,13 @@ const rpcHandler = createRpcHandler({
blockchainClient,
});

// Initialize error tracker
const errorTracker = createErrorTracker({
enabled: true,
snapName: 'gator-permissions-snap',
snapProvider: snap,
});

// configure RPC methods bindings
const boundRpcHandlers: {
[RpcMethod: string]: (params?: JsonRpcParams) => Promise<Json>;
Expand Down Expand Up @@ -226,27 +236,44 @@ export const onRpcRequest: OnRpcRequestHandler = async ({
origin,
request,
}) => {
logger.debug(`RPC request (origin="${origin}"): method="${request.method}"`);

// Ensure i18n is initialized on every snap invocation
// This handles both initial load and locale changes in the extension
await setupI18n();

if (!isMethodAllowedForOrigin(origin, request.method)) {
throw new InvalidRequestError(
`Origin '${origin}' is not allowed to call '${request.method}'`,
try {
logger.debug(
`RPC request (origin="${origin}"): method="${request.method}"`,
);
}

const handler = boundRpcHandlers[request.method];

if (!handler) {
throw new MethodNotFoundError(`Method ${request.method} not found.`);
// Ensure i18n is initialized on every snap invocation
// This handles both initial load and locale changes in the extension
await setupI18n();

if (!isMethodAllowedForOrigin(origin, request.method)) {
throw new InvalidRequestError(
`Origin '${origin}' is not allowed to call '${request.method}'`,
);
}

const handler = boundRpcHandlers[request.method];

if (!handler) {
throw new MethodNotFoundError(`Method ${request.method} not found.`);
}

const result = await handler(request.params);

return result;
} catch (error) {
// Fire-and-forget: do not await so the original error is always rethrown.
// If captureError throws (e.g. shouldTrackError or #extractErrorInfo), we must not lose the app error.
errorTracker
.captureError({
error,
method: request?.method ?? 'unknown',
requestParams: request?.params,
})
.catch(() => {
// Swallow tracking failures; caller must always receive the original error.
});
throw error;
}

const result = await handler(request.params);

return result;
};

/**
Expand Down
48 changes: 37 additions & 11 deletions packages/permissions-kernel-snap/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
import { logger } from '@metamask/7715-permissions-shared/utils';
import {
logger,
createErrorTracker,
} from '@metamask/7715-permissions-shared/utils';
import {
InvalidParamsError,
LimitExceededError,
Expand All @@ -21,6 +24,13 @@ const rpcHandler = createRpcHandler({
snapsProvider: snap,
});

// Initialize error tracker
const errorTracker = createErrorTracker({
enabled: true,
snapName: 'permissions-kernel-snap',
snapProvider: snap,
});

// configure RPC methods bindings
const boundRpcHandlers: {
[RpcMethod: string]: (options: {
Expand Down Expand Up @@ -54,19 +64,22 @@ export const onRpcRequest: OnRpcRequestHandler = async ({
origin,
request,
}) => {
// Check if another request is already being processed
if (activeProcessingLock !== null) {
logger.warn(
`RPC request rejected (origin="${origin}"): another request is already being processed`,
);
throw new LimitExceededError('Another request is already being processed.');
}

// Acquire the processing lock
// Create unique lock token
const myLock = Symbol('processing-lock');
activeProcessingLock = myLock;

try {
// Check if another request is already being processed
if (activeProcessingLock !== null) {
logger.warn(
`RPC request rejected (origin="${origin}"): another request is already being processed`,
);
throw new LimitExceededError(
'Another request is already being processed.',
);
}

// Acquire the processing lock
activeProcessingLock = myLock;
logger.info(
`Custom request (origin="${origin}"): method="${request.method}"`,
);
Expand Down Expand Up @@ -103,6 +116,19 @@ export const onRpcRequest: OnRpcRequestHandler = async ({
});

return result;
} catch (error) {
// Fire-and-forget: do not await so the lock is released in finally without
// blocking on auxiliary error tracking (lock serializes request processing only).
errorTracker
.captureError({
error,
method: request?.method ?? 'unknown',
requestParams: request?.params,
})
.catch(() => {
// Swallow tracking failures; lock release must not depend on tracking.
});
throw error;
} finally {
// Always release the processing lock we acquired, regardless of success or failure
// Only release if we still hold the lock to avoid clobbering a newer lock
Expand Down
1 change: 1 addition & 0 deletions packages/shared/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
"test": "jest"
},
"dependencies": {
"@metamask/snaps-sdk": "10.2.0",
"@metamask/utils": "11.4.2",
"dotenv": "17.2.0",
"zod": "3.25.76"
Expand Down
203 changes: 203 additions & 0 deletions packages/shared/src/utils/errorTracking.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,203 @@
import { getJsonError } from '@metamask/snaps-sdk';

import { logger } from './logger';

/**
* Error information that will be tracked.
*/
export type ErrorTrackingInfo = {
snapName: string;
method: string;
url?: string | undefined;
statusCode?: number | undefined;
errorMessage: string;
errorStack?: string | undefined;
responseData?: any | undefined;
requestParams?: any | undefined;
};

/**
* Error tracking service configuration.
*/
export type ErrorTrackingConfig = {
enabled: boolean;
snapName: string;
snapProvider: any;
shouldTrackError?: (error: any) => boolean;
};

/**
* Error tracking service for snaps.
* Provides a unified way to track and report errors across different snaps.
*/
export class SnapErrorTracker {
readonly #enabled: boolean;

readonly #snapName: string;

readonly #snapProvider: any;

readonly #shouldTrackError: (error: any) => boolean;

constructor(config: ErrorTrackingConfig) {
this.#enabled = config.enabled;
this.#snapName = config.snapName;
this.#snapProvider = config.snapProvider;
this.#shouldTrackError =
config.shouldTrackError ??
((error: any): boolean => {
// By default, track Error instances, string errors, or objects with error-like properties
return (
error instanceof Error ||
typeof error === 'string' ||
(typeof error === 'object' &&
error !== null &&
(error?.message !== undefined || error?.error !== undefined))
);
});
}

/**
* Extracts error information from various error formats.
*
* @param error - The error to extract information from.
* @param method - The method/operation that triggered the error.
* @param requestParams - Optional request parameters that triggered the error.
* @returns The extracted error information.
*/
#extractErrorInfo(
error: any,
method: string,
requestParams?: any,
): ErrorTrackingInfo {
const errorInfo: ErrorTrackingInfo = {
snapName: this.#snapName,
method,
errorMessage: 'Unknown error',
};

// Check if the error has a currentUrl property
if (error?.currentUrl) {
errorInfo.url = error.currentUrl;
}

// Handle different error formats (align with shouldTrackError: use !== undefined so
// falsy values like '' or null are preserved for Sentry instead of "Unknown error")
if (error instanceof Error) {
errorInfo.errorMessage = error.message;
errorInfo.errorStack = error.stack;
} else if (typeof error === 'string') {
errorInfo.errorMessage = error;
} else if (
typeof error === 'object' &&
error !== null &&
'message' in error &&
error.message !== undefined
) {
errorInfo.errorMessage = String(error.message);
} else if (
typeof error === 'object' &&
error !== null &&
'error' in error &&
error.error !== undefined
) {
if (typeof error.error === 'string') {
errorInfo.errorMessage = error.error;
} else {
try {
errorInfo.errorMessage = JSON.stringify(error.error);
} catch {
errorInfo.errorMessage = String(error.error);
}
}
}

// Get status code if available
if (error?.status) {
errorInfo.statusCode = error.status;
} else if (error?.statusCode) {
errorInfo.statusCode = error.statusCode;
}

// Get response data if available
if (error?.response) {
errorInfo.responseData = error.response;
} else if (error?.data) {
errorInfo.responseData = error.data;
}

// Get request params if available (from parameter or error object)
if (requestParams !== undefined) {
errorInfo.requestParams = requestParams;
} else if (error?.requestParams) {
errorInfo.requestParams = error.requestParams;
} else if (error?.params) {
errorInfo.requestParams = error.params;
}

return errorInfo;
}

/**
* Tracks an error using the snap's error tracking mechanism.
* This function safely handles error tracking without throwing additional errors.
*
* @param errorInfo - The error information to track.
*/
async #trackErrorViaSnap(errorInfo: ErrorTrackingInfo): Promise<void> {
try {
// Use snap_trackError if available
if (this.#snapProvider?.request) {
await this.#snapProvider.request({
method: 'snap_trackError',
params: {
error: getJsonError(new Error(JSON.stringify(errorInfo))),
},
});
}
} catch (trackingError) {
// Silently fail - don't let error tracking itself break the app
logger.warn(
'[SnapErrorTracker] Failed to track error via snap:',
trackingError,
);
}
}

/**
* Captures and tracks an error.
*
* @param errorData - The error data object containing error, method, and optional requestParams.
* @param errorData.error - The error to capture.
* @param errorData.method - The method/operation name.
* @param errorData.requestParams - Optional request parameters that triggered the error.
*/
async captureError({
error,
method,
requestParams,
}: {
error: any;
method: string;
requestParams?: any;
}): Promise<void> {
if (!this.#enabled || !this.#shouldTrackError(error)) {
return;
}

const errorInfo = this.#extractErrorInfo(error, method, requestParams);
await this.#trackErrorViaSnap(errorInfo);
}
}

/**
* Creates an error tracker instance.
*
* @param config - Configuration for the error tracker.
* @returns The error tracker instance.
*/
export function createErrorTracker(
config: ErrorTrackingConfig,
): SnapErrorTracker {
return new SnapErrorTracker(config);
}
1 change: 1 addition & 0 deletions packages/shared/src/utils/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
export * from './common';
export * from './error';
export * from './logger';
export * from './errorTracking';
Loading
Loading