Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
1 change: 1 addition & 0 deletions packages/snap-networks-utils/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

### Changed

- Change the default `shouldTrack` of `createTrackError` and `createSnapErrorHandling` to also skip errors a fetch policy already reported (`isReportedFetchPolicyError`) ([#642](https://github.com/MetaMask/internal-snaps/pull/642))
- Change `requiresMaliciousAcknowledgement` to accept the security-alerts preference and verdict, treating a missing preference as disabled, and allow `TransactionAlert` callers to select the unavailable-scan banner severity ([#578](https://github.com/MetaMask/internal-snaps/pull/578))

### Fixed
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { SnapError, UserRejectedRequestError } from '@metamask/snaps-sdk';
import type { Mock } from 'vitest';

import { BrokenCircuitError } from '../fetchPolicy/createFetchPolicy';
import { mockLogger } from '../logger/__mocks__/Logger';
import type { TrackErrorFn } from './errors';
import { createSnapErrorHandling, createTrackError } from './trackError';
Expand Down Expand Up @@ -32,6 +33,18 @@ describe('trackError', () => {
expect(request).not.toHaveBeenCalled();
});

it('does not track errors a fetch policy already reported', async () => {
const { request, trackError } = setupTrackErrorTest();

expect(
await trackError(
new Error('Request failed', { cause: new BrokenCircuitError() }),
),
).toBeUndefined();

expect(request).not.toHaveBeenCalled();
});

it('tracks errors and returns the Sentry event id', async () => {
const { request, trackError } = setupTrackErrorTest();
const originalError = new Error('Test error');
Expand Down
9 changes: 7 additions & 2 deletions packages/snap-networks-utils/src/utils/errors/trackError.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { getJsonError, UserRejectedRequestError } from '@metamask/snaps-sdk';
import type { TrackErrorParams, TrackErrorResult } from '@metamask/snaps-sdk';
import { ensureError } from '@metamask/utils';

import { isReportedFetchPolicyError } from '../fetchPolicy/createFetchPolicy';
import type {
CreateWithCatchAndThrowSnapErrorOptions,
LogErrorFn,
Expand Down Expand Up @@ -56,7 +57,10 @@ function defaultPrepareError(error: unknown): Error {
}

function defaultShouldTrack(error: unknown): boolean {
return !(error instanceof UserRejectedRequestError);
return !(
error instanceof UserRejectedRequestError ||
isReportedFetchPolicyError(error)
);
}

/**
Expand All @@ -69,7 +73,8 @@ function defaultShouldTrack(error: unknown): boolean {
* @param options.getSnapProvider - Returns the Snap provider used for `snap_trackError`.
* @param options.logError - Logger method used when the tracking RPC fails.
* @param options.prepareError - Optional error normalizer before Sentry serialization.
* @param options.shouldTrack - Optional filter; defaults to skipping `UserRejectedRequestError`.
* @param options.shouldTrack - Optional filter; defaults to skipping `UserRejectedRequestError`
* and errors a fetch policy already reported (see `isReportedFetchPolicyError`).
* @returns A function that reports errors to Sentry when {@link ShouldTrackErrorFn} allows it.
*/
export function createTrackError<TProvider extends TrackErrorCapableProvider>({
Expand Down
9 changes: 1 addition & 8 deletions packages/solana-wallet-snap/src/core/utils/errors.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,4 @@
import {
createSnapErrorHandling,
isReportedFetchPolicyError,
} from '@metamask/snap-networks-utils';
import { UserRejectedRequestError } from '@metamask/snaps-sdk';
import { createSnapErrorHandling } from '@metamask/snap-networks-utils';

import logger from './logger';
import { getSnapProvider } from './snap';
Expand All @@ -14,7 +10,4 @@ export const { trackError, withCatchAndThrowSnapError } =
createSnapErrorHandling({
getSnapProvider,
logError: logger.error.bind(logger),
shouldTrack: (error) =>
!(error instanceof UserRejectedRequestError) &&
!isReportedFetchPolicyError(error),
});
7 changes: 7 additions & 0 deletions packages/stellar-wallet-snap/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

- Add the `getMaxSendableAmount` client request method, returning the maximum amount that would pass `onAmountInput` for XLM and classic assets. XLM leaves the minimum reserve and the inclusion fee, token balances require XLM to cover the fee, and the result is `0` when no amount can pass ([#594](https://github.com/MetaMask/internal-snaps/pull/594))

### Changed

- Report Horizon, Stellar RPC, Price API, Token API and Security Alerts API outages through the shared fetch policy ([#642](https://github.com/MetaMask/internal-snaps/pull/642))
- Outages send the "Snap Service Degraded" and "Snap Service Unavailable" Segment events.
- Stellar RPC, Price API, Token API and Security Alerts API calls that use up their retries are reported to Sentry once, sanitised, and callers no longer report them again.
- Horizon keeps its current Sentry reporting, because the Stellar SDK rethrows Horizon read failures as new errors that callers can't recognise as already reported.

## [2.1.0]

### Changed
Expand Down
11 changes: 3 additions & 8 deletions packages/stellar-wallet-snap/src/context.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import {
AnalyticsService,
createFetchPolicy,
SecurityAlertsApiClient,
State,
Expand Down Expand Up @@ -72,7 +71,8 @@ import {
import { TransactionScanService } from './services/transaction-scan';
import { WalletService } from './services/wallet';
import { ConfirmationUXController } from './ui/confirmation/controller';
import { getSnapProvider, logger, noOpLogger, trackError } from './utils';
import { logger, noOpLogger, trackError } from './utils';
import { analyticsService, fetchPolicyReporting } from './utils/analytics';

assert(AppConfig, object());

Expand All @@ -86,12 +86,6 @@ const transactionRepository = new TransactionRepository(state);
const assetMetadataRepository = new AssetMetadataRepository(state);

/** ------------------------------ Services ------------------------------ */
const analyticsService = new AnalyticsService({
getSnapProvider,
logger,
trackError,
});

const appCache = new InMemoryCache(noOpLogger);
const networkService = new NetworkService({ logger, cache: appCache });

Expand Down Expand Up @@ -158,6 +152,7 @@ const securityAlertsApiClient = new SecurityAlertsApiClient({
policy: createFetchPolicy({
service: 'security_alerts_api',
logger: logger.withPrefix('[🛡️ SecurityAlertsApiClient]'),
...fetchPolicyReporting,
}),
});

Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import * as snapNetworksUtils from '@metamask/snap-networks-utils';
import { buildUrl } from '@metamask/snap-networks-utils';
import type { MockedFunction } from 'vitest';

import { KnownCaip2ChainId } from '../../../api';
import { fetchPolicyReporting } from '../../../utils/analytics';
import {
HttpException,
HttpResponseException,
Expand Down Expand Up @@ -52,6 +54,22 @@ describe('TokenApiClient', () => {

const createClient = () => new TokenApiClient({ baseUrl }, mockFetch);

it('reports outages through its fetch policy', () => {
const createFetchPolicySpy = vi.spyOn(
snapNetworksUtils,
'createFetchPolicy',
);

createClient();

expect(createFetchPolicySpy).toHaveBeenCalledWith(
expect.objectContaining({
service: 'token_api',
...fetchPolicyReporting,
}),
);
});

describe('getAssetsByAssetIds', () => {
it('requests token API with assetIds in query and returns parsed body', async () => {
const body = [
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import type {
} from '../../../api';
import type { AnyErrorConstructor } from '../../../utils';
import { rethrowIfInstanceElseThrow } from '../../../utils';
import { fetchPolicyReporting } from '../../../utils/analytics';
import {
assertHttpRequestParams,
assertHttpResponse,
Expand Down Expand Up @@ -56,6 +57,7 @@ export class TokenApiClient {
this.#policy = createFetchPolicy({
service: 'token_api',
logger: _logger,
...fetchPolicyReporting,
});
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { TransactionStatus } from '@metamask/keyring-api';
import * as snapNetworksUtils from '@metamask/snap-networks-utils';
import { InMemoryCache } from '@metamask/snap-networks-utils';
import type { CreateFetchPolicyOptions } from '@metamask/snap-networks-utils';
import {
Account,
Horizon as StellarHorizon,
Expand All @@ -12,6 +14,7 @@ import { BigNumber } from 'bignumber.js';
import { KnownCaip2ChainId } from '../../api';
import { AppConfig } from '../../config';
import { toSmallestUnit } from '../../utils';
import { analyticsService, fetchPolicyReporting } from '../../utils/analytics';
import { logger } from '../../utils/logger';
import {
TESTNET_SEP41_USDC,
Expand Down Expand Up @@ -66,6 +69,37 @@ describe('NetworkService', () => {
scope = KnownCaip2ChainId.Mainnet;
});

it('reports Horizon outages to analytics only, and RPC outages to analytics and Sentry', async () => {
const createFetchPolicySpy = vi.spyOn(
snapNetworksUtils,
'createFetchPolicy',
);
getHorizonClientSpies().fetchBaseFeeSpy.mockResolvedValue(100);
getRpcServerSpies().getAccountSpy.mockRejectedValue(new Error('boom'));

await networkService.getBaseFee(scope);
await expect(
networkService.getAccount(generateStellarAddress(), scope),
).rejects.toThrow(NetworkServiceException);

const optionsFor = (
service: string,
): CreateFetchPolicyOptions | undefined =>
createFetchPolicySpy.mock.calls.find(
([options]) => options.service === service,
)?.[0];
expect(optionsFor('stellar_horizon')).toStrictEqual(
expect.objectContaining({
chainIdCaip: scope,
analytics: analyticsService,
}),
);
expect(optionsFor('stellar_horizon')).not.toHaveProperty('trackError');
expect(optionsFor('stellar_rpc')).toStrictEqual(
expect.objectContaining({ chainIdCaip: scope, ...fetchPolicyReporting }),
);
});

describe('getBaseFee', () => {
it('returns base fee as BigNumber', async () => {
const { fetchBaseFeeSpy } = getHorizonClientSpies();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import {
batchesAllSettled,
getAssetReference,
} from '../../utils';
import { analyticsService, fetchPolicyReporting } from '../../utils/analytics';
import { OnChainAccount } from '../on-chain-account/OnChainAccount';
import { InvalidInvokeContractStructureException } from '../transaction/exceptions';
import { Transaction } from '../transaction/Transaction';
Expand Down Expand Up @@ -87,6 +88,9 @@ export class NetworkService {
service: 'stellar_horizon',
chainIdCaip: scope,
logger: this.#logger,
// No `trackError`: the SDK rethrows Horizon read failures as new
// errors without `cause`, so callers would report them again.
analytics: analyticsService,
}),
this.#getNetworkConfig(scope).horizonUrl,
this.#getNetworkConfig(scope).timeout,
Expand All @@ -104,6 +108,7 @@ export class NetworkService {
service: 'stellar_rpc',
chainIdCaip: scope,
logger: this.#logger,
...fetchPolicyReporting,
}),
this.#getNetworkConfig(scope).rpcUrl,
this.#getNetworkConfig(scope).timeout,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import * as snapNetworksUtils from '@metamask/snap-networks-utils';
import { buildUrl } from '@metamask/snap-networks-utils';
import type { MockedFunction } from 'vitest';

import { fetchPolicyReporting } from '../../../utils/analytics';
import {
HttpException,
HttpResponseException,
Expand Down Expand Up @@ -44,6 +46,22 @@ describe('PriceApiClient', () => {

const createClient = () => new PriceApiClient({ baseUrl }, mockFetch);

it('reports outages through its fetch policy', () => {
const createFetchPolicySpy = vi.spyOn(
snapNetworksUtils,
'createFetchPolicy',
);

createClient();

expect(createFetchPolicySpy).toHaveBeenCalledWith(
expect.objectContaining({
service: 'price_api',
...fetchPolicyReporting,
}),
);
});

describe('getSpotPrices', () => {
it('requests spot prices with default vsCurrency', async () => {
const spotBody = {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import type { CaipAssetType } from '@metamask/utils';

import type { AnyErrorConstructor } from '../../../utils';
import { rethrowIfInstanceElseThrow } from '../../../utils';
import { fetchPolicyReporting } from '../../../utils/analytics';
import {
assertHttpRequestParams,
assertHttpResponse,
Expand Down Expand Up @@ -46,6 +47,7 @@ export class PriceApiClient {
this.#policy = createFetchPolicy({
service: 'price_api',
logger: _logger,
...fetchPolicyReporting,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

im wondering why we dont move those api client into the share utils first, as they should be the same

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

They could, but the problem today is that they differ (Bitcoin is on /v1 with a different response; Solana and Tron add caching and chunking; Stellar doesn't). Moving them is a refactor across 4 snaps so we could do it but it's a PR own its own imo not related to this one.

});
}

Expand Down
20 changes: 20 additions & 0 deletions packages/stellar-wallet-snap/src/utils/analytics.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { AnalyticsService } from '@metamask/snap-networks-utils';

import { trackError } from './errors';
import { logger } from './logger';
import { getSnapProvider } from './snap';

export const analyticsService = new AnalyticsService({
getSnapProvider,
logger,
trackError,
});

/**
* Spread into every `createFetchPolicy` call so outages emit Segment events
* and give-ups reach Sentry.
*/
export const fetchPolicyReporting = {
analytics: analyticsService,
trackError,
};
32 changes: 32 additions & 0 deletions packages/stellar-wallet-snap/src/utils/errors.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import {
createFetchPolicyError,
FetchPolicyErrorName,
} from '@metamask/snap-networks-utils';
import { UserRejectedRequestError } from '@metamask/snaps-sdk';

import {
HttpException,
Expand All @@ -12,6 +13,7 @@ import {
KnownHttpErrorCode,
normalizeHttpException,
rethrowIfInstanceElseThrow,
trackError,
} from './errors';

describe('errors', () => {
Expand Down Expand Up @@ -105,6 +107,36 @@ describe('errors', () => {
});
});

describe('trackError', () => {
it('does not track errors a fetch policy already reported', async () => {
expect(await trackError(new BrokenCircuitError())).toBeUndefined();
expect(
await trackError(
new HttpException('HTTP error!', {
cause: new BrokenCircuitError(),
}),
),
).toBeUndefined();

expect(snap.request).not.toHaveBeenCalled();
});

it('does not track user rejections', async () => {
expect(await trackError(new UserRejectedRequestError())).toBeUndefined();

expect(snap.request).not.toHaveBeenCalled();
});

it('tracks other errors', async () => {
await trackError(new Error('boom'));

expect(snap.request).toHaveBeenCalledWith({
method: 'snap_trackError',
params: { error: expect.objectContaining({ message: 'boom' }) },
});
});
});

describe('InvalidHttpRequestParamsException', () => {
it('can be constructed with a message', () => {
expect(new InvalidHttpRequestParamsException('bad params').message).toBe(
Expand Down
4 changes: 2 additions & 2 deletions packages/stellar-wallet-snap/vitest.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,8 +47,8 @@ export default mergeConfig(
thresholds: {
branches: 77.83,
functions: 87.36,
lines: 88.41,
statements: 88.37,
lines: 88.42,
statements: 88.38,
},
},
},
Expand Down
Loading
Loading